我在我的(Spring Framework + Spring Data + Hibernate JPA)项目中有一个单向的OneToMany JPA实体映射。实体类类似于以下代码。(为简洁起见,我删除了无关的类成员。)
@Entity
@Table(name = "employees")
class Employee{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "employee_id")
private List<DepartmentAssignment> departmentAssignments = new ArrayList<>();
}
@Entity
@Table(name = "department_assignments")
class DepartmentAssignment{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@NotNull
@Column(name = "employee_id")
private Integer employeeId;
@NotNull
@Column(name = "department_id")
private Integer departmentId;
}
@Entity
@Table(name = "departments")
class Department{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
}
并且,在我的一个服务类中有一个从Employee中删除DepartmentAssignment的方法,如下所示。
public Employee deleteDepartmentAssignment(Integer empId, Integer deptAssignmentId) {
Employee employee = employeeRepository.findOne(empId);
if(employee != null) {
for ( DepartmentAssignment da : employee.getDepartmentAssignments()) {
if(da.getId().equals(deptAssignmentId)) {
employee.getDepartmentAssignments().remove(da);
employee = employeeRepository.save(employee);
break;
}
}
}
return employee;
}
但是,调用上面的方法会给我一个错误:org.hibernate.exception.ConstraintViolationException
,在SQL日志中,我可以看到事件的最后一个SQL语句出现Column 'employee_id' cannot be null
错误。
有人可以告诉我这里我做错了什么以及如何解决这个问题?
答案 0 :(得分:1)
您无需添加
@NotNull
@Column(name = "employee_id")
private Integer employeeId;
如果您使用Employee
,请到@JoinColumn(name = "employee_id")
。尝试删除它。
答案 1 :(得分:1)
您可以尝试以下操作,不确定为什么在对象中使用plain id。那不是对象关系映射。 有关详细信息,请参阅Hibernate triggering constraint violations using orphanRemoval
@Entity
@Table(name = "employees")
class Employee{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "employee", orphanRemoval = true)
private List<DepartmentAssignment> departmentAssignments = new ArrayList<>();
}
@Entity
@Table(name = "department_assignments")
class DepartmentAssignment{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne(optional=false)
private Employee employee;
@ManyToOne(optional=false)
private Department department;
}
@Entity
@Table(name = "departments")
class Department{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
}
答案 2 :(得分:0)
您必须查看 .hbm.xml 文件,并且应该将您的实体映射到此文件中 你可以看看这个例子
http://www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example/
我希望它对你有用。
答案 3 :(得分:-1)
尝试删除
cascade = CascadeType.ALL
但我不是100%肯定..