Wednesday, January 7, 2009

JPA: Retrieving ID of Recently Persisted Object

Using JPA with an orm.xml, I was having trouble retrieving the primary key (id) of a recently persisted object. The entity in my orm.xml:

<entity class="Foo" name="Foo" access="FIELD">
<table name="Foo"/>
<attributes>
<id name="id">
<column name="ID" nullable="false"/>
<generated-value strategy="SEQUENCE"/>
</id>
...
</table>
</entity>
The relevant MySQL for the table:
CREATE TABLE FOO
(
ID INT NOT NULL AUTO_INCREMENT,
...
PRIMARY KEY(ID)
)
Regardless of whether or not the id property was null or not, it was not updated after the following call to persist():
Foo foo = new Foo();
getJpaTemplate().persist(foo);
if (logger.isDebugEnabled())
logger.debug(foo.getId()) // null

Adding a call to flush() however ended up giving me the id:
Foo foo = new Foo();
getJpaTemplate().persist(foo);
getJpaTemplate().flush();
if (logger.isDebugEnabled())
logger.debug(foo.getId()) // outputs the assigned id
I'm not sure why the flush() was necessary. A similar issue is also discussed here: Spring Forums Post.

5 comments: