我正在用java开发一个小型的Spring和hibernate基础应用程序,我的应用程序与Employee和Unit有一对多的关系,Employee有一个单元,Unit有很多Employee。在这个小应用程序中会产生这样的错误`
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:列“unit_id”不能为空
如果允许空值到 unit_id 插入的其他数据没有插入 unit_id
这是我的实体类
@Entity
@Table(name = "employee")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "epf")
private int epf;
@Column(name = "fname")
private String fname;
@Column(name = "lname")
private String lname;
@Column(name = "email")
private String email;
@JoinColumn(name = "unit_id", referencedColumnName = "id")
@ManyToOne//(optional = false)
private Unit unit;
@Entity
@Table(name = "unit")
public class Unit implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "name")
我的控制器类
@RequestMapping(value="/employee.do", method=RequestMethod.POST)
public ModelAndView doActions(@ModelAttribute Employee emp, BindingResult result, @RequestParam String action, Map<String, Object> map){
ModelAndView modelAndView = new ModelAndView("employee");
Employee employeetResult = new Employee();
switch(action.toLowerCase()){ //only in Java7 can put String in switch
case "add":
employeeService.addEmployee(emp);
employeetResult = emp;
break;
case "edit":
employeeService.updateEmployee(emp);
employeetResult = emp;
break;
case "delete":
employeeService.deleteEmployee(emp.getId());
employeetResult = new Employee();
break;
case "search":
Employee searchedStudent = employeeService.getEmployee(emp.getId());
employeetResult = searchedStudent!=null ? searchedStudent : new Employee();
break;
}
map.put("employee", employeetResult);
map.put("employeeList", employeeService.getAllEmployee());
return modelAndView;
}
我的 DAO 课程
> @Repository public class EmployeeDaoImp implements EmployeeDao {
>
> @Autowired private SessionFactory sessionfactory;
> public void addEmployee(Employee emp) { sessionfactory.getCurrentSession().save(emp);
>
> }
>
> public void updateEmployee(Employee emp) {
> sessionfactory.getCurrentSession().update(emp);
>
> }
>
> public void deleteEmployee(int id) {
> sessionfactory.getCurrentSession().delete(getEmployee(id)); }
>
> Employee public Employee getEmployee(int empId) {
> return (Employee) sessionfactory.getCurrentSession().get(Employee.class,empId); }
>
> public List getAllEmployee() {
> return sessionfactory.getCurrentSession().createQuery("from Employee").list(); }