私はJavaでSpringとHibernateの小さなベースアプリケーションを開発しています。私のアプリケーションはEmployee と Unit と1対多の関係にあり、 Employee には1つのユニットがあり、 Unit には多くの Employee があります。この小さなアプリケーションでは、次のようなエラーが生成されます `
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 列 'unit_id' を null にすることはできません
unit_id に null 値を許可する場合、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(); }