users@glassfish.java.net

Re: OneToMany: sequence of steps to ensure synchronization?

From: <glassfish_at_javadesktop.org>
Date: Fri, 06 Jul 2007 14:51:24 PDT

Basically, you just need to ensure that the children have links to the parent in this case.

So...

[code]
PostalAddress pa = new PostalAddress();
ArrayList l = new ArrayList();
PostalAddressLine pl1 = new PostalAddressLine();
PostalAddressLine pl2 = new PostalAddressLine();

pl1.setPostalAddress(pa);
pl2.setPostalAddress(pa);
l.add(pl1);
l.add(pl2);
pa.setPostalAddressLines(l);
em.merge(pa);
[/code]

If you are using a sequence generator for your primay keys (otherwise you need to set up your keys yourself), then this is all you have to do. In the end you should have a PostalAddress row, and 2 PostalAddressLine rows, with the foreign keys managed properly.

This is the "easy" part, IMHO. The more difficult part is handling row deletions, particularly with detached objects.

EntityManager.merge will readily update a single row, but does not have any "smarts" for propagating changes across relationships.

Specifically, in the case above, if you were to take that PostalAddress, as a detached object, and then remove one of the PostalAddressLines, and then merge back the PostalAddress, JPA will NOT delete the "missing" line for you automatically. You need to make an effort to synchronize lists like that yourself.

However, if you were to take the object, and simply add a new line, that new line would be added and updated properly just like the first time.

So, that's just a pitfall you need to be aware of as you work with the JPA.
[Message sent by forum member 'whartung' (whartung)]

http://forums.java.net/jive/thread.jspa?messageID=225565