I have table employee and table employee_detail, I can add data to non related table(employee), controller work fine, everything is okey, but I cant implement code so I can store data to related table employee_detail
Employee:
#Entity
#Table(name="employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "employeeId")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#OneToOne(mappedBy = "employee")
private EmployeeDetail employeeDetail;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public EmployeeDetail getEmployeeDetail() {
return employeeDetail;
}
public void setEmployeeDetail(EmployeeDetail employeeDetail) {
this.employeeDetail = employeeDetail;
}
}
EmployeeDetail:
#Entity
#Table(name = "employee_detail")
public class EmployeeDetail {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="employee_detail_id")
private int id;
#Column(name="work_experience")
private int workExperience;
#Column(name="hobby")
private String hobby;
#Column(name="nationality")
private String nationality;
#OneToOne
#JoinColumn(name="employeeId")
private Employee employee;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getWorkExperience() {
return workExperience;
}
public void setWorkExperience(int workExperience) {
this.workExperience = workExperience;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
This is how I store data to employee table:
`EmployeeController:`
#Controller
#RequestMapping("/employee")
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
#GetMapping("/list")
public String listEmployee(Model theModel) {
// get customers from the service
List<Employee> theEmployee = employeeService.listEmployee();
// add the customers to the model
theModel.addAttribute("employees", theEmployee);
return "list-employee";
}
#GetMapping("/showFormForAdd")
public String showFormForAdd(Model theModel) {
// create model attribute to bind form data
Employee theEmployee = new Employee();
theModel.addAttribute("employee", theEmployee);
return "addNewEmployeeForm";
}
#PostMapping("/addNewEmployee")
public String addNewEmployee(#ModelAttribute("employee") Employee theEmployee) {
// save the customer using our service
employeeService.addNewEmployee(theEmployee);
return "redirect:/employee/list";
}
}
And form addNewEmployeeForm:
<form:form action="addNewEmployee" modelAttribute="employee" method="POST">
<table>
<tbody>
<tr>
<td><label>First name:</label></td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td><label>Last name:</label></td>
<td><form:input path="lastName" /></td>
</tr>
<tr>
<td><label>Email:</label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save" class="save" /></td>
</tr>
</tbody>
</table>
How to store data into table from related table? What m I missing?
I tried like this but doesnt work:
#Controller
#RequestMapping("/employeeDetail")
public class EmployeeDetailController {
#Autowired
private EmployeeDetailService employeeDetailService;
#GetMapping("/listEmployeeDetail")
public String listEmployeeDetail(Model theModel) {
// get customers from the service
List<EmployeeDetail> theEmployeeDetail = employeeDetailService.listEmployeeDetail();
// add the customers to the model
theModel.addAttribute("employeeDetails", theEmployeeDetail);
return "list-employeeDetail";
}
#GetMapping("/showFormForAddEmployeeDetail")
public String showFormForAddEmployeeDetail(Model theModel) {
// create model attribute to bind form data
EmployeeDetail theEmployeeDetail = new EmployeeDetail();
theModel.addAttribute("employeeDetail", theEmployeeDetail);
return "addNewEmployeeDetailForm";
}
#PostMapping("/addNewEmployeeDetail")
public String addNewEmployeeDetail(#ModelAttribute("employeeDetail") EmployeeDetail theEmployeeDetail) {
// save the customer using our service
employeeDetailService.addNewEmployeeDetail(theEmployeeDetail);
return "redirect:/employeeDetail/listEmployeeDetail";
}
}
Requested code:
#Override
#Transactional
public void addNewEmployeeDetail(EmployeeDetail theEmployeeDetail) {
employeeDetailDAO.addNewEmployeeDetail(theEmployeeDetail);
}
Assuming your are not actively saving the EmployeeDetail entities on your own and only saving Employee, then configure cascade attribute on #OneToOne relationship on Employee side as follows:
#OneToOne(mappedBy = "employee", cascade = CascadeType.ALL)
private EmployeeDetail employeeDetail;
With this, you are telling your EntityManager to propagate (cascade) all operations (PERSIST, REMOVE, REFRESH, MERGE, DETACH) to the relating entities.
In addition to the change above, I would also recommend you moving to JPA instead of handling Hibernate Sessions on your own.
Include the Spring Boot JPA dependency in your pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Create two repositories, one for each entity and inject them into the corresponding Service (just like you are doing with your DAOs):
public interface EmployeeDAO extends JpaRepository<Employee, Integer> {
}
public interface EmployeeDetailDAO extends JpaRepository<EmployeeDetail, Integer> {
}
Now in your Services, you can call a couple of default methods on these Repositories such as findAll() or save(). In your case you would do something like the following:
#Override
#Transactional
public void addNewEmployee(Employee theEmployee) {
employeeDAO.save(theEmployee);
}
You can check more details at https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa and https://www.baeldung.com/spring-data-repositories.
Keep in mind that you will have a hard time saving EmployeeDetail directly as you receive it from your form. The reason being that you need to set Employee attribute, otherwise the foreign key in the column employeeId would be set and thus you will get a SQL error.
Related
I have a Spring Boot project, in which when i create new account successfully, the property of that account returns null in the database
Controller class
import javax.validation.Valid;
#Controller
#RequestMapping("/music/backend/user")
public class UserController {
#Autowired
UserService userService;
#GetMapping("list")// Phương thức Get: Lấy dữ liệu ==> load trang ra dự form có sẵn trước
// #ResponseBody// trả về dạng json
public String list(Model model,
#RequestParam(name = "name",
required = false) String name){
//model: chuyền biến từ java -> jsp
Object obj= null;
if(name==null){
obj=userService.findAll();
}else{
obj=userService.searchByEmail(name);
}
model.addAttribute("title", name);
model.addAttribute("list", obj);
return "/jsp/list.jsp";
}
#GetMapping("create")
public String create(Model model,
#RequestParam(name = "name",
required = false) String name){
//model: chuyền biến từ java -> jsp
// Object authors= userService.findAllAuthor();
model.addAttribute("title", "Tạo Mới User");
UserDto userDto= new UserDto();
model.addAttribute("userDto",userDto);
// model.addAttribute("authors", authors);
return "/jsp/signup.jsp";
}
// #GetMapping("edit/{id}")// Phương thức Get: Lấy dữ liệu
// public String create(Model model, #PathVariable Integer id){
//// Object authors = bookService.findAllAuthor();
// model.addAttribute("user", userService.getById(id));
// model.addAttribute("title", "Cập nhật tài khoản");
//// model.addAttribute("authors", authors);
// return "/jsp/user_edit.jsp";
// }
#GetMapping("delete/{id}")
public String delete(RedirectAttributes redirectAttributes, #PathVariable Integer id){
userService.deleteById(id);
redirectAttributes.addFlashAttribute("message", "Xóa thành công");
return "redirect:/music/backend/user/list";
}
#PostMapping(value = "save", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String save( UserDto userDto,
Model model, RedirectAttributes redirectAttributes) {
userService.save(userDto);
redirectAttributes.addFlashAttribute("message", "Tạo mới thành công");
return "redirect:/music/backend/user/list";
}
}
UserDto class
#Data
public class UserDto {
private int id;
private String username;
private String email;
private String password;
private String sex;
private Date dob;
}
UserEntity class
import javax.persistence.*;
import java.sql.Date;
import java.util.Objects;
#Entity
#Table(name = "user", schema = "ktpm", catalog = "")
public class UserEntity {
private Integer id;
private String username;
private String email;
private String password;
private String sex;
private Date dob;
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Basic
#Column(name = "user_name")
public String getUserName() {
return username;
}
public void setUserName(String username) {
this.username = username;
}
#Basic
#Column(name = "user_email")
public String getUserEmail() {
return email;
}
public void setUserEmail(String email) {
this.email = email;
}
#Basic
#Column(name = "user_password")
public String getUserPassword() {
return password;
}
public void setUserPassword(String password) {
this.password = password;
}
#Basic
#Column(name = "user_sex")
public String getUserSex() {
return sex;
}
public void setUserSex(String sex) {
this.sex = sex;
}
#Basic
#Column(name = "user_date")
public Date getUserDate() {
return dob;
}
public void setUserDate(Date dob) {
this.dob = dob;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserEntity that = (UserEntity) o;
return Objects.equals(id, that.id) &&
Objects.equals(username, that.username) &&
Objects.equals(email, that.email) &&
Objects.equals(password, that.password) &&
Objects.equals(sex, that.sex) &&
Objects.equals(dob, that.dob);
}
#Override
public int hashCode() {
return Objects.hash(id, username, email, password, sex, dob);
}
}
UserService class
#Service
public class UserService {
#Autowired
UserRepository userRepository;
public String save(UserDto userDto) {
UserEntity userEntity = new UserEntity();
BeanUtils.copyProperties(userDto, userEntity);
// lưu vào db
userRepository.save(userEntity);
return "tạo mới thành công ";
}
public List<UserEntity> findAll(){
return userRepository.findAll();
}
public UserEntity getById(Integer id){
return userRepository.findById(id).get(); // sự # giữa orm và jdbc
}
public String deleteById(Integer id){
userRepository.deleteById(id);
return "xóa thành công";
}
public List<UserEntity> searchByEmail(String email){
return userRepository.findAllByUserEmailContaining(email);
}
}
user_list.jsp
Danh sách book:
${title}
<br>
<h2 class="color-red" >${message}</h2>
<a class="color-red" href="/backend/user/create">Tạo mới</a>
<br>
<input id="search" value="${title}"/> <button onclick="searchClick()">Tìm kiếm</button>
<script>
function searchClick() {
var name = document.getElementById("search").value;
window.location.href = "/backend/user/list?name="+name;
}
</script>
<table>
<thead>
<th>Email</th>
<th>Họ và tên</th>
<th>Địa chỉ</th>
<th>Ngày sinh</th>
<th>Hành động</th>
</thead>
<tbody>
<c:forEach items="${list}" var="s">
<tr>
<td>${s.email}</td>
<td>${s.fullName}</td>
<td>${s.address}</td>
<td>${s.dateOfBirth}</td>
<td>Xóa</td>
</tr>
</c:forEach>
</tbody>
</table>
when i create new account successfully, the property of that account returns null in the database, how should i fix it
What dependency are you using for BeanUtils ?
org.apache.commons.beanutils
or
org.springframework.beans.
For the first one BeanUtils.copyProperties(Object res, Object src), for the second this is BeanUtils.copyProperties(Object src, Object res).
This is a spring mvc app and this is part of it. When I insert category id to the form, it moves me to this error:
but when I removed the category id input from the form, the data inserted to the database.
Product.java
#Entity
#Table(name = "product", catalog = "flowershop")
public class Product implements java.io.Serializable {
private Integer id;
private Category categoryid;
private String name;
private Double price;
public Product() {
}
public Product(Category categoryid, String name, Double price) {
this.categoryid = categoryid;
this.name = name;
this.price = price;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "categoryid",foreignKey = #ForeignKey(name = "Product_categoryid_productid"))
public Category getCategoryid() {
return this.categoryid;
}
public void setCategoryid(Category categoryid) {
this.categoryid = categoryid;
}
#Column(name = "name", length = 45)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "price", precision = 22, scale = 0)
public Double getPrice() {
return this.price;
}
public void setPrice(Double price) {
this.price = price;
}
}
Category.java
#Entity
#Table(name="category", catalog="flowershop")
public class Category implements java.io.Serializable {
private Integer id;
private String name;
private Set<Product> products = new HashSet<Product>(0);
public Category() {
}
public Category(String name, Set<Product> products) {
this.name = name;
this.products = products;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="id", unique=true, nullable=false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name="name", length=45)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="categoryid")
public Set<Product> getProducts() {
return this.products;
}
public void setProducts(Set<Product> products) {
this.products = products;
}
}
ProductDAOImp.java
#Repository("productDAO")
public class ProductDAOImp implements ProductDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public void newProduct(Product product) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(product);
tx.commit();
session.close();
}
ProductServiceImp.java
#Service("productService")
#Transactional
public class ProductServiceImp implements ProductService {
#Override
public void newProduct(Product product) {
productDAO.newProduct(product);
}
}
ProductController.java
#Controller
#Transactional
#RequestMapping("/product")
public class ProductController {
#Autowired
private CategoryService categoryService;
#Autowired
private ProductService productService;
#RequestMapping(value = "category/{id}", method = RequestMethod.GET)
public String category(#PathVariable("id") Integer id, ModelMap modelMap) {
Category category = categoryService.find(id);
Hibernate.initialize(category.getProducts());
modelMap.put("products", category.getProducts());
return "product.category";
}
#RequestMapping(value = {"newProduct"}, method = RequestMethod.GET)
public String newProduct(ModelMap modelMap) {
Product product = new Product();
modelMap.put("newProduct", product);
modelMap.put("title", "New Product");
return "product.newProduct";
}
#RequestMapping(value = {"newProduct"}, method = RequestMethod.POST)
public String newProduct(
#ModelAttribute("newProduct") Product product,
ModelMap modelMap) {
modelMap.put("newProduct", product);
try {
productService.newProduct(product);
return "product.newProduct";
} catch (Exception e) {
return "product.newProduct";
}
}
}
newProduct.jsp
<f:form method="POST" modelAttribute="newProduct" action="${pageContext.request.contextPath}/product/newProduct.html">
<div class="form_row">
<label class="contact"><strong>Name: </strong></label>
<input name="name" type="text" class="contact_input"/>
</div>
<div class="form_row">
<label class="contact"><strong>Price: </strong></label>
<input name="price" type="text" class="contact_input"/>
</div>
<div class="form_row">
<label class="contact"><strong>Category Id: </strong></label>
<input name="categoryid" type="text" class="contact_input"/>
</div>
<div class="form_row">
<input type="submit" class="register" value="register">
</div>
</f:form>
this annotation #GeneratedValue(strategy = IDENTITY) is automatically assign an id to record. so in your project you desired to use manually generated id, please remove this.
This webapp is made with spring boot connected to MariaDB .I would like to view the items in each category, I can see the category attributes and can see the item in the view as such [Item [id=1, title=test, description=11, status=Used, zipcode=1231, price=111.0, category=Category [id=3, type=Services]]]
heres my controller
#RequestMapping(value="/item-by-category/{id}",method= RequestMethod.GET)
public String itemByCategory(#PathVariable("id") Long categoryid, Model model){
//model.addAttribute("items",irepository.findByCategory(categoryid));
model.addAttribute("categorys",crepository.findOne(categoryid));
//model.addAttribute("item",irepository.findByCategory(categoryid));
return "/item-by-category";
}
Im using CRUD repositories so I tried to use the itemRepository method to filter the items by category but I get an error on the type of attribute passed even if its of type Long as stated in the class initiation.
Repositories:
public interface ItemRepository extends CrudRepository<Item, Long> {
List<Item> findByTitle(String title);
List<Item> findByCategory(Long categoryid);
}
public interface CategoryRepository extends CrudRepository<Category, Long> {
//find by cat type
List<Category> findByType(String type);
//List<Category>findByItem(String item);
//Item findByCategory(String type);
//show the items in the categories
//List<Item>items(String type);
//List<Category>findByItem(String item);
}
classes :
#Entity
#Table(name="category")
public class Category {
//#id creates an ID column for the table
#Id
//Generates automatically a unique PK for every new entity object
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="categoryid")
private Long id;
#Column(name="type")
private String type;
// 1 Category can have * Items
#OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
private List<Item> item;
//constructor
public Category() {}
public Category(String type) {
super();
this.type = type;
}
//getters n setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
//getters n setters for relationship
public List<Item> getItems() {
return item;
}
public void setItems(List<Item> item) {
this.item = item;
}
#Override
public String toString() {
return "Category [id=" + id + ", type=" + type + "]";
}
}
#Entity
#Table(name="item")
public class Item {
//generated ID column
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="itemid")
private Long id;
#Column(name="title")
private String title;
#Column(name="description")
private String description;
#Column(name="status")
private String status;
#Column(name="zipcode",length=5)
private Integer zipcode;
#Column(name="price")
private Double price;
//create relationship or * to 1 between items to user
/*
#ManyToOne
#JsonIgnore
#JoinColumn(name = "userid")
private User user;
*/
//Many items can have 1 category * to 1
#ManyToOne
/*entity relationship will
cause endless loop (First item is serialized and it contains
category which is then serialized which contains students which
are then serialized
*/
#JsonIgnore
#JoinColumn(name = "categoryid")
private Category category;
//working ^^
//JPA constructor
public Item(){
}
public Item(Long id, String title, String description, String status, Integer zipcode, Double price,
Category category) {
super();
this.id = id;
this.title = title;
this.description = description;
this.status = status;
this.zipcode = zipcode;
this.price = price;
this.category = category;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getZipcode() {
return zipcode;
}
public void setZipcode(Integer zipcode) {
this.zipcode = zipcode;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
#Override
public String toString() {
return "Item [id=" + id + ", title=" + title + ", description=" + description + ", status=" + status
+ ", zipcode=" + zipcode + ", price=" + price + ", category=" + category + "]";
}
}
so tried taking the category and got it working so far like this:
<table class="table table-striped">
<tr th:each ="category : ${categorys}">
<td th:text="${category.id}" ></td>
<td th:text="${category.items}" ></td>
//shows the size of the array
<td th:text="${category.items.size()}" ></td>
</tr>
<!-- this is what I want as the result, I would like to know how to loop with the TH attribute
<tr>
<td th:text="${category.items[0].title}"></td>
<td th:text="${category.items[0].category.type}"></td>
<td th:text="${category.items[0].description}"></td>
<td th:text="${category.items[0].status}"></td>
<td th:text="${category.items[0].zipcode}"></td>
<td th:text="${category.items[0].price}"></td>
</tr>
-->
This is my first web app using Spring mvc, at this point I am a bit stuck and would appreciate it if someone pointed me towards the right path thank you :D
To achieve a nested loop in Thymeleaf, simply do the following:
<th:block th:each="category : ${categorys}">
<tr th:each="item : ${category.items}">
<td th:text="${category.item.title}"></td>
<td th:text="${category.item.category.type}"></td>
<td th:text="${category.item.description}"></td>
<td th:text="${category.item.status}"></td>
<td th:text="${category.item.zipcode}"></td>
<td th:text="${category.item.price}"></td>
</tr>
</th:block>
I was able to achieve the result asked without the nested loops. by changing the parameter type to Category which is the attribute type in the entity class.
Repository:
List<Item> findByCategory(Category categoryid);
Controller :
#RequestMapping(value="/item-by-category/{id}",method= RequestMethod.GET)
public String itemByCategory(#PathVariable("id") Category categoryid, Model model){
model.addAttribute("items",irepository.findByCategory(categoryid));
return "/itemlist";
}
This is my semester.java class
#Entity
#Table(name = "semester")
#NamedQueries({
#NamedQuery(name = "Semester.findAll", query = "SELECT s FROM Semester s")})
public class Semester implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#OneToMany(mappedBy = "semesterid")
private List<Marks> marksList;
#JoinColumn(name = "facultyid", referencedColumnName = "facultyid")
#ManyToOne
private Faculty facultyid;
#JoinColumn(name = "semesterid", referencedColumnName = "semesterid")
#ManyToOne
private Semestername semesterid;
#JoinColumn(name = "subjectcode", referencedColumnName = "subjectcode")
#ManyToOne
private Subject subjectcode;
public Semester() {
}
public Semester(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<Marks> getMarksList() {
return marksList;
}
public void setMarksList(List<Marks> marksList) {
this.marksList = marksList;
}
public Faculty getFacultyid() {
return facultyid;
}
public void setFacultyid(Faculty facultyid) {
this.facultyid = facultyid;
}
public Semestername getSemesterid() {
return semesterid;
}
public void setSemesterid(Semestername semesterid) {
this.semesterid = semesterid;
}
public Subject getSubjectcode() {
return subjectcode;
}
public void setSubjectcode(Subject subjectcode) {
this.subjectcode = subjectcode;
}
}
This is the admin controller
#Controller
public class AdminController {
#Autowired
AdminDao adminDao;
#RequestMapping(value="/addsemester",method=RequestMethod.GET)
public String addsemester(Model model){
model.addAttribute("semesterlist", new Semester());
return "semesterentry";
}
#RequestMapping(value="/addsemester",method=RequestMethod.POST)
public String _addsemester(#ModelAttribute("semesterlist") Semester semester){
boolean check = adminDao.insertsemester(semester);
if(check){
return "redirect:/addsemester";
}
else{
return "dashboard";
}
}
}
This is the admindaoImpl.java class and when i used to insert the semester 400 error with the syntically incorrect was faced.
#Repository("adminDao")
public class AdminDaoImpl implements AdminDao {
#Autowired
SessionFactory sessionFactory;
#Transactional
public boolean insertsemester(Semester semester){
boolean check = false;
try {
sessionFactory.getCurrentSession().save(semester);
} catch (Exception e) {
}
if(sessionFactory.getCurrentSession().save(semester)!=null){
check = true;
}
return check;
}
}
and when i try to insert the data to database i got 400 error. and i have check all the value of jsp name with database again i got a problem on these.
You have to use modelAttribute in <form:form tag instead of <form.
<form:form method="post" modelAttribute="semesterlist" action="${pageContext.servletContext.contextPath}/addsemester" >
<form:label path="semesterid">Semester ID</form:label>
<form:input path="semesterid"/>
<!-- provide the rest of fields -->
<input type="submit" value="add" /> <input type="reset" value="cancel"/>
</form:form>
And in controller:
#RequestMapping(value="/addsemester",method=RequestMethod.POST)
public String _addsemester(#ModelAttribute("semesterlist") Semester semester){
...........
}
The below data is stored in MongoDB. I am using Spring-Data and storing the data into mongoDB.
If I want to retrieve the fields ("id" or "Name") I can able to do, but if I want to retrieve the sub fields ("firstName" or "lastName")I can't.
(eg.)If I want to retrieve sub field "lastName" from the below data I can't.Can anyone help me in this regards.
Thanks in advance.
Data Stored in MongoDB:
{
"id":101,
"name": {"firstName":"Mark",
"lastName":"Antony"
}
}
The Code I am using is:
PersonService.java
public List<Audit> searchPerson(Audit audit)
{
List<NameDetails> name=audit.getName();
return mongoTemplate.find(new Query(Criteria.where("name.lastName").is(name.get(0))), Audit.class,COLLECTION_NAME);
}
PersonController.java
#RequestMapping(value = "/person/search", method = RequestMethod.GET)
public String search(#ModelAttribute Audit audit, ModelMap model) {
model.addAttribute("personList", personService.searchPerson(audit));
return "output";
}
Audit.java
#Document
public class Audit {
#Id
private String id;
private List<NameDetails> name;
public String getId() {
System.out.println("Person: getId");
return id;
}
public void setId(String id) {
System.out.println("Person: setId");
this.id = id;
}
public List<NameDetails> getName() {
System.out.println("Audit: getName");
return name;
}
public void setName(List<NameDetails> name) {
System.out.println("Audit: setName");
this.name = name;
}
}
NameDetails.java
package com.register.mongo.model;
public class NameDetails {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
System.out.println("NameDetails: setFirstName");
this.firstName = firstName;
}
public String getLastName() {
System.out.println("NameDetails: getLastName");
return lastName;
}
public void setLastName(String lastName) {
System.out.println("NameDetails: setLastName");
this.lastName = lastName;
}
}
(output.jsp)UI Page
<table border="2">
<c:forEach var="person" items="${personList}">
<tr>
<td>${person.id}</td>
</tr>
<tr>
<td>${person.lastName}</td>
</tr>
</c:forEach>
</table>
If i understand well, you should make an extra class and use it in the Audit class
public class NameDetails{
private String FirstName;
private String LastName;
public String getFirstName() {
return id;
}
public void seFirstName(String fisrtName) {
this.FirstName= fisrtName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
}
and use this class in the Audit.class
#Document
public class Audit {
#Id
private String id;
private List name<NameDetails>;
and then the setters and getters