Results 1 to 6 of 6

Thread: Get id of JPA persisted object

  1. #1
    Join Date
    Dec 2008
    Location
    Oslo, Norway
    Posts
    2

    Default Get id of JPA persisted object

    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

  2. #2
    Join Date
    Mar 2008
    Location
    Wayzata, MN
    Posts
    15

    Default

    This should happen automatically. For example, if your Model object is defined with an id like:

    Code:
    @Entity
    @Table
    public class Foo
    {
        @Id()
        @GeneratedValue
        @Column(nullable = false)
        private Long id;
    And a database table (MySQL syntax):

    Code:
    CREATE TABLE foo(
    id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT
    ) Engine = InnoDB DEFAULT CHARSET=utf8;
    Then when you define in your dao

    Code:
    public void save(Foo entity)
    {
        entityManager.persist(entity);
    }
    After the save() (or persist()) call, the ID should be available in the entity (it gets set by jpa).

  3. #3
    Join Date
    Dec 2008
    Location
    Oslo, Norway
    Posts
    2

    Thumbs up

    You are of course absolutely right.
    Thanks for your help.

  4. #4
    Join Date
    Jul 2008
    Posts
    3

    Default

    I'm having a similar issue using an orm.xml and getJpaTemplate():

    Code:
    getJpaTemplate().persist(foo);
    The foo object has an id before the call to persist().

    The entity mapping in orm.xml:

    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>
    My tables is created in MySQL with:
    Code:
    CREATE TABLE FOO
    (
        ID       INT              NOT NULL AUTO_INCREMENT,
    ...
        PRIMARY KEY(ID),
    
    );
    After the call to persist(), the id of the Foo object is not updated, maybe I'm missing something?
    Thanks

  5. #5
    Join Date
    Jul 2008
    Posts
    3

    Default

    A call to flush() seemed to do the trick:
    Code:
    getJpaTemplate().persist(foo);
    getJpaTemplate.flush()

  6. #6
    Join Date
    Dec 2009
    Posts
    2

    Default Doesn't work with Oracle DB

    Anybody had any luck making this work with an Oracle back-end

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •