Hi
I am using JPA through Spring for persistence.
Allocation of object ids are done by the database.
When persisting an object I would like to get the allocated object id back.
Is there any possibility to do this?
Best regards,
POV
Hi
I am using JPA through Spring for persistence.
Allocation of object ids are done by the database.
When persisting an object I would like to get the allocated object id back.
Is there any possibility to do this?
Best regards,
POV
This should happen automatically. For example, if your Model object is defined with an id like:
And a database table (MySQL syntax):Code:@Entity @Table public class Foo { @Id() @GeneratedValue @Column(nullable = false) private Long id;
Then when you define in your daoCode:CREATE TABLE foo( id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT ) Engine = InnoDB DEFAULT CHARSET=utf8;
After the save() (or persist()) call, the ID should be available in the entity (it gets set by jpa).Code:public void save(Foo entity) { entityManager.persist(entity); }
You are of course absolutely right.
Thanks for your help.
I'm having a similar issue using an orm.xml and getJpaTemplate():
The foo object has an id before the call to persist().Code:getJpaTemplate().persist(foo);
The entity mapping in orm.xml:
My tables is created in MySQL with:Code:<entity class="Foo" name="Foo" access="FIELD"> <table name="Foo"/> <attributes> <id name="id"> <column name="ID" nullable="false"/> <generated-value strategy="SEQUENCE"/> </id> ... </entity>
After the call to persist(), the id of the Foo object is not updated, maybe I'm missing something?Code:CREATE TABLE FOO ( ID INT NOT NULL AUTO_INCREMENT, ... PRIMARY KEY(ID), );
Thanks
A call to flush() seemed to do the trick:
Code:getJpaTemplate().persist(foo); getJpaTemplate.flush()
Anybody had any luck making this work with an Oracle back-end