0

I have the usual parent - child OneToMany relationship:

@OneToMany(mappedBy = "mapType", cascade = CascadeType.ALL, orphanRemoval = true)
public List<Child> getChildren() {
    return children;
}

I have fairly standard use cases:

  • Must delete children on persist- this works fine.

  • Add new children by adding to collection. This works fine for already persisted parents, but does not work for new parents. EntityManager.merge however does persist the new parent with the new children.

Why would adding new children not work for new Parent objects? They're definitely there before persist is called.

I'm on Hibernate 3.6.6 by the way.

Will
  • 877
  • 11
  • 25
  • 2
    http://stackoverflow.com/questions/4509086/what-is-the-difference-between-persist-and-merge-in-hibernate/4509389#4509389 – NimChimpsky Sep 28 '11 at 11:41
  • Yes, I have read and understood the semantics. If you read my question, you'll see I get different behaviour persisting child entities, depending on whether the parent object is new or not. This is not explained by your link, or the many other articles I have read. – Will Sep 28 '11 at 12:25
  • It seems that if persist is called _before_ setting the child entities, the cascade works. OTOH, if persist is called _after_ setting the child entities, the cascade does not occur. Is this expected behaviour? – Will Sep 28 '11 at 12:48

1 Answers1

0

Try to add this attribute in @OneToMany annotation fetch = FetchType.EAGER. Default value is LAZY. It'll be helpful because hibernate will be manage collection permanently then you make changes.

Yappie
  • 399
  • 2
  • 8
  • Unfortunately this doesn't help as the issue is with new entities, not ones that are fetched by hibernate. Also I have two lists of child entities on one entity and hibernate does not support eager loading of multiple bags on an entity! – Will Sep 30 '11 at 16:47
  • that way you select to say the hibernate about which item in the collection of any place? – Yappie Sep 30 '11 at 17:26
  • 1
    Setting EAGER fetch in entity's annotation is detrimental in 80 % of cases. Causes unwanted fetching which can't be overriden when using `find()`, nor in HQL/JPAQL. Also may cause cross-fetching, ending up with whole 2 tables loaded. – Ondra Žižka Jul 21 '12 at 22:29