Adding items to a lazy loading many-to-many Set (and saving the entity) doesn't trigger the appropriate INSERT SQL query, so the new relations are not saved, when the parent entity has an @ElementCollection field too.
A self-contained demo is available in
, it's runnable with mvn clean test.
I've experienced this issue both with Hibernate ORM 5.1.0 and 5.2.0; but 5.0.9 seems to be working fine.
I've found that any of the following changes make it work again (see the demo app):
Uncomment the parent.getNames(); command at Main.java:75.
Remove the names field, and the getNames() and setNames(Set<String>) methods of the Parent entity.
Change the fetch attribute of the @ManyToMany annotation to FetchType.EAGER.
Set enableLazyInitialization to false in pom.xml.
Change Hibernate's version to 5.0.9 in pom.xml (there are two instances).
Performing any of these changes makes the insert into parents_children (parent, child) values (?, ?) SQL command appear in the standard output.
Hibernate does have a Maven repository with the latest sources at http://snapshots.jboss.org/maven2/. For latest hibernate-core see http://snapshots.jboss.org/maven2/org/hibernate/hibernate-core/5.2.1-SNAPSHOT/
, I have changed my demo project to use the 5.2.1-SNAPSHOT versions by applying
At the time of writing, the snapshot versions were hibernate-core-5.2.1-20160628.131959-62 and hibernate-enhance-maven-plugin-5.2.1-20160628.132014-61.
Unfortunately, the issue is still present: mvn clean test still prints
Hibernate: delete from parents_children where parent=?
java.lang.RuntimeException: Child count is 0. Child hasn't been added to parent?!
I was finally able to use the sample you provided to create a proper test case that reproduces the issue. With the test case and with the awesome analysis you did, I came up with a fix not much different than what you suggested. PR: https://github.com/hibernate/hibernate-orm/pull/1461
Fixed in master, 5.1, and 5.0 branches.