Announcement Announcement Module
Collapse
No announcement yet.
Get id of JPA persisted object Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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
    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).

    Comment


    • #3
      You are of course absolutely right.
      Thanks for your help.

      Comment


      • #4
        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

        Comment


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

          Comment


          • #6
            Doesn't work with Oracle DB

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

            Comment

            Working...
            X