The following (simplified version of our) code passes our JUnit tests under Hibernate, but not under EclipseLink. What is needed to make this work under EclipseLink?
public static void store(EntityManager em, String a, String b) {
Entry entry=new Entry();
entry.setFirst(a);
entry.setLast(b);
em.persist(entry);
em.persist(new SubEntry(entry.getId(), a, b));
}
It fails because entry.getId() is returning 0 when using EclipseLink. What is the appropriate way to retrieve the unique identifier of an object that has just been stored?
It appears obvious that the above code doesn’t make sense, as doing an entry.getId() before the transaction has been committed probably does not make sense, however hibernate allowed it.
There are a few things going on here. Unless you provide some of the code for your entity classes, we can’t know what kind of strategy you are using for primary key generation. Let me assume that you’re using a strategy that allows the database to generate a primary key for your
Entryclass, such as a sequence or auto-number column. Let me further assume that you’re calling this method inside an active transaction. If you insert a call toem.flush()right after your call toem.persist(entry)then I think this will work, given the assumptions that I stated above.The unknown that I see is whether or not
entryis a reference to a managed entity when you make the second call toem.persist()and whether or not it has been assigned an id (primary key) value yet.