Java 如果Employee中有另一个对象,如何在JSP中正确保存Employee
员工实体:Java 如果Employee中有另一个对象,如何在JSP中正确保存Employee,java,spring,hibernate,jsp,spring-mvc,Java,Spring,Hibernate,Jsp,Spring Mvc,员工实体: @Entity @Table(name = "EMPLOYEE") public class Employee { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @ManyToOne(targetEntity = Department.class) @JoinColumn(name = "department_id") private Department department; @Colum
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@ManyToOne(targetEntity = Department.class)
@JoinColumn(name = "department_id")
private Department department;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
@Column(name = "SALARY")
private int salary;
EmployeeDao具有两个变量路径来保存员工:
@Override
@Transactional(readOnly = false)
public void addEmployee(int departmentId, String firstName, String lastName, int salary) {
Department department = getDepartmentById(departmentId);
Employee employee = new Employee(department, firstName, lastName, salary);
sessionFactory.getCurrentSession().save(employee);
}
@Override
@Transactional(readOnly = false)
public void addEmployee(Employee employee) {
sessionFactory.getCurrentSession().save(employee);
}
主控制器:
@RequestMapping(value = "/employee/add", method = RequestMethod.GET)
public ModelAndView addPage(Model model) {
model.addAttribute("emp", new Employee());
List<Department> departments = dao.getAllDepartments();
model.addAttribute("deps", departments);
return new ModelAndView("Add");
}
@RequestMapping(value = "/employee/add", method = RequestMethod.POST)
public ModelAndView addEmployee(@ModelAttribute("emp") Employee employee) {
System.out.println(employee);
//dao.addEmployee(employee);
return new ModelAndView("redirect:/");
}
帮助,请不要传递子id,您可以直接传递带有相应键的对象并保存实体 i、 e.用此标签替换您的选择标签
<select>
<c:forEach var="dep" items="${deps}">
<option name="department" value="${dep}"> ${dep.name}</option>
</c:forEach>
</select>
${dep.name}
或
如果您只想通过传递子对象的主键来实现这一点,那么可以使用带有spring验证器的@InitBinder
来识别子对象
提及
注意:在rest方法中,您是通过按部门id获取部门来添加员工的,因此工作正常,并且在jsp post请求中,您传递的员工实体只是部门id,而不是部门对象
@RequestMapping(value = "/add/employee/{departmentId}/{firstName}/{lastName}/{salary}", method = RequestMethod.POST, headers = "Accept=application/json")
public void addEmployee(@PathVariable int departmentId,@PathVariable String firstName,@PathVariable String lastName,@PathVariable int salary) {
dao.addEmployee(departmentId, firstName, lastName, salary);
dao.calculateAvgSalaryInDepartment();
}
<select>
<c:forEach var="dep" items="${deps}">
<option name="department" value="${dep}"> ${dep.name}</option>
</c:forEach>
</select>