users@glassfish.java.net

Re: getting null primary key

From: <glassfish_at_javadesktop.org>
Date: Tue, 04 Sep 2007 07:48:12 PDT

I'm not sure what cascade options you have set the country->user relation to use, but since country is already managed, merge is a no-op on it. That, and the merge really doesn't garantee setting ids till after the flush/commit, and only on the managed copy of an object. So in the case of:

Country country = (Country)em.find(Country.class, countryid);
user.setCountry(country);
country.getUserinfoCollection().add(user);
em.merge(country);

The user object will not be managed after the merge call. It will be found during a flush or commit and inserted, but your handle to the user object never becomes managed (merge makes a copy of the object it finds and manages it instead).

Persist called on a new User object should always assign sequencing, so if you are finding cases where it isn't, you should identify how to reproduce the issue and file a bug. ie:
  user.setCountry(new Country(id));
  em.persist(user);
  user.getUserId();
though you should run into problems if the Country object is created with an existing id.

To get the IDs reliably, I'd use:
  em.persist(user);
  Country country = (Country)em.find(Country.class, countryid);
  user.setCountry(country);
  country.getUserinfoCollection().add(user);
  em.flush();

There is no need to merge the country (or user) since both are managed.

Best Regards,
Chris
[Message sent by forum member 'chris_delahunt' (chris_delahunt)]

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