java - Hibernate duplicates elements in parent collection while it is populating with newly persisted childs -
can explain following strange behaviour encountered? trying persist new child objects , simultaneously add them to parent collection. @ end there twice many elements in parent collection expected. let me show example:
@entity public class { @generatedvalue(strategy = generationtype.identity) @id private integer id; @onetomany(mappedby = "a") private list<b> bs = new arraylist<>(); public integer getid() { return id; } public void setid(integer id) { this.id = id; } public list<b> getbs() { return bs; } public void setbs(list<b> bs) { this.bs = bs; } } @entity public class b { @generatedvalue(strategy = generationtype.identity) @id private integer id; @manytoone private a; public integer getid() { return id; } public void setid(integer id) { this.id = id; } public geta() { return a; } public void seta(a a) { this.a = a; } }
test case:
@test public void test() throws exception { entitymanager.gettransaction().begin(); a = new a(); entitymanager.persist(a); entitymanager.flush(); entitymanager.clear(); = entitymanager.find(a.class, a.getid()); (int = 0; < 3; i++) { b b = new b(); b.seta(a); entitymanager.persist(b); a.getbs().add(b); } assertequals(3, a.getbs().size()); entitymanager.gettransaction().commit(); }
result:
java.lang.assertionerror: expected :3 actual :6
i don't ask how modify given code achieve expected result. want understand why given code behaves this.
update: works fine eclipselink , datanucleus, fails hibernate.
thanks @riskop answer , further investigation can summarize:
- eclipselink 2.5.0 - it works expected.
- datanucleus 4.1.9 - it works expected.
- hibernate 5.1.0.final, 5.0.3.final 4.3.11.final, 4.2.21.final,... - it doesn't work.
unfortunately can't tell how happening
but hibernate bug. should return 3.
i checked hibernate 5.0.3.final , experienced same problem. checked exact same code datanucleus 4.1.9 , works expected (no duplicate size of collection).
however, hibernate problem goes away if of following:
- not using @generatedvalue(strategy = generationtype.identity). generationtype.identity discouraged, , can source of other problems (just google it). if change auto, hibernate works ok.
- change eager fetching on entity ( @onetomany(mappedby = "a", fetch=fetchtype.eager)
- initializes collection on after loading database (via calling a.getbs().size() example).
Comments
Post a Comment