I have a model which has 2 oneToMany relation to another 2 model. When i remove 1 record from first bag and save the object, hibernate removes 1 record from 1st bag which is ok but it also removes the record which has same index as the record in first bag from 2nd bag. I can not figure it out how to fix it.
Here is my models
Owner:
@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);
}
}
Dog:
@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;
}
}
Cat:
@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;
}
}
Let say we had an owner which has 2 cats and 2 dogs.
when i do that:
Cat cat2Remove = owner.getCats().get(1);
owner.removeCat(cat2Remove);
session.save(owner);
Hibernate removes 2nd cat from table_b as i intend but it also removes 2nd dog from table_c and i wonder how can i prevent this in a proper way?