Hibernate One-to-Many Unidirectional Conversion Generates Redundant Updates
I have defined two classes: "Parent and Child". The parent may have a list of children.
@Entity
public class Parent {
@Id
@GeneratedValue(...)
@SequenceGenerator(...)
private long id;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "parent_id", referencedColumnName = "id", nullable = false)
private List<Child> children;
public Parent() {
children = new ArrayList<Child>();
}
public void addChild(Child child) { children.add(child); }
}
@Entity
public class Child {
@Id
@GeneratedValue(...)
@SequenceGenerator(...)
private long id;
// The "Child" table in the db also has a not-null "parent_id" column.
}
If I add the list to the list and keep the parent, everything works as expected: Hibernate gets the sequence values, stores the parent, and then stores all the children.
However, after doing all this, it will update all children by setting "parent_id" to the value that was already set in insert!
The generated SQL looks like this:
insert into PARENT (id) values (1)
insert into CHILD (parent_id, id) values (1, 1)
insert into CHILD (parent_id, id) values (1, 2)
insert into CHILD (parent_id, id) values (1, 3)
update CHILD set parent_id = 1 WHERE id = 1
update CHILD set parent_id = 1 WHERE id = 2
update CHILD set parent_id = 1 WHERE id = 3
If I make this association bi-directional it works fine, but then I need a parent reference in my child class and something I want to avoid.
The repository is a Spring Data JPA datastore:
public interface ParentRepository extends PagingAndSortingRepository<Parent, Long> {}
(simplified) code that creates and stores objects:
Parent parent = new Parent();
parent.addChild(new Child());
parent.addChild(new Child());
repo.save(parent);
Any suggestions?
+3
source to share