我有一个模型,该模型与另一个2模型具有2 oneToMany关系。当我从第一个包中删除1条记录并保存对象时,hibernate从第一个包中删除1条记录,这还可以,但它也会从第二个包中删除与第一个包中的记录具有相同索引的记录。我不知道如何解决它。
这是我的模特
所有者:
@Entity
@Table(name = "table_a")
public class Owner extends Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id", unique = true, nullable = false)
private int id;
@OneToMany(mappedBy = "owner", fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.ALL)
@OrderColumn(name = "position")
private List<Dog> dogs;
@OneToMany(mappedBy = "owner", fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.ALL)
@OrderColumn(name = "position")
private List<Cat> cats;
public Long getId() {
this.id;
}
public void setId(Long id) {
this.id = id;
}
public Dog getDogs() {
return this.dogs;
}
public void setDogs(List<Dog> dogs) {
this.dogs = dogs;
}
public void addDog(Dog dog) {
dog.owner = this;
this.dogs.add(dog);
}
public void removeDog(Dog dog) {
this.dogs.remove(dog);
}
public Dog getCats() {
return this.cats;
}
public void setCats(List<Cat> cats) {
this.cats = cats;
}
public void addCat(Cat cat) {
Cat.owner = this;
this.cats.add(cat);
}
public void removeCat(Cat cat) {
this.cats.remove(cat);
}
}
狗:
@Entity
@Table(name = "table_b")
public class Dog extends Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id", unique = true, nullable = false)
private int id;
@ManyToOne
@JoinColumn(name = "owner_id")
private Owner owner;
@Column(name = "position")
private int position;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public int getPosition() {
return this.position;
}
public void setPosition(int index) {
this.position = index;
}
public Owner getOwner() {
return this.owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
}
猫:
@Entity
@Table(name = "table_c")
public class Cat extends Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id", unique = true, nullable = false)
private int id;
@ManyToOne
@JoinColumn(name = "owner_id")
private Owner owner;
@Column(name = "position")
private int position;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public int getPosition() {
return this.position;
}
public void setPosition(int index) {
this.position = index;
}
public Owner getOwner() {
return this.owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
}
假设我们有一个拥有2只猫和2条狗的主人。
当我这样做时:
Cat cat2Remove = owner.getCats().get(1);
owner.removeCat(cat2Remove);
session.save(owner);
Hibernate按我的意愿从table_b中删除了第二只猫,但也从table_c中删除了第二只狗,我想知道如何以适当的方式防止这种情况发生?
最佳答案
发生这种情况的原因是cascade = CascadeType.ALL
,因此您必须删除CascadeType.ALL
才能了解级联的影响,请参见this链接。
如果只想级联保存更新,请使用cascade="save-update"
我不知道您是否需要orphanRemoval = true
,但请查看these答案以了解您是否需要它。