[英]Bug Hibernate OneToMany/ManyToOne
I'm trying to make a relationship using OneToMany and ManyToOne, but when I try to insert a record into database without add a object(class) in the list OneToMany, the hibernate try to insert the record OneToMany anyway. 我正在尝试使用OneToMany和ManyToOne建立关系,但是当我尝试将记录插入数据库而不在列表OneToMany中添加对象(类)时,休眠模式无论如何都会尝试插入记录OneToMany。 Example: Employee Class:
示例:员工类别:
@Entity
public class Employee implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy="employee")
private List<Shift> shifts = new ArrayList<Shift>();
}
Shift Class: 班次:
@Entity
public class Shift implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.DETACH)
@JoinColumn(name="EMPLOYEE_ID")
private Employee employee;
}
When I try to insert the record: 当我尝试插入记录时:
Employee employee = new Employee();
entityManager.persist(employee);
entityManager.flush();
How can I fix it? 我该如何解决? I'm using SQL Server Database.
我正在使用SQL Server数据库。
14:53:49,660 INFO [stdout] (default task-20) Hibernate: insert into Employee
14:53:49,762 INFO [stdout] (default task-20) Hibernate: insert into Shift(EMPLOYEE_ID) values (?)
As per my understanding,It is because of you have specified cascade = CascadeType.ALL
in the Employee
class. 据我了解,这是因为您在
Employee
类中指定了cascade = CascadeType.ALL
。
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy="employee")
private List<Shift> shifts = new ArrayList<Shift>();
Which means,when you will make any operation on Employee
object,it will cascade it to Shift
class too,due to this. 这意味着,当您对
Employee
对象进行任何操作时,由于此原因,它也将其级联到Shift
类。
For ref see here :- CascadeType 有关参考,请参见此处: -CascadeType
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.