Why JPA persist() does not generated auto-increment primary ID?

帅比萌擦擦* 提交于 2019-11-30 04:18:49

问题


I'm using JPA toplink-essential and SQL Server 2008

My goal is to get auto-increment primary key value of the data that is going to be inserted into the table. I know in JDBC, there is getInsertedId() like method that give you the id of auto-increment primary id (but that's after the insert statement executed though)

In JPA, I found out @GenratedValue annotation can do the trick.

@Entity
@Table(name = "tableOne")
public class TableOne implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "tableId")
    private Integer tableId;

Now if I run the code below it should give me the auto incremented id but it returns NULL...

 EntityManager em = EmProvider.getInstance().getEntityManagerFactory().createEntityManager();
 EntityTransaction txn = em.getTransaction();
 txn.begin();

 TableOne parent = new TableOne();
 em.persist(parent); //here I assume that id is pre-generated for me.
 System.out.println(parent.getTableId()); //this returns NULL :(

回答1:


We are also using SQL Server 2008 and it never worked for me so I always execute separate query "SELECT @@IDENTY" to get the inserted id.

The reason I found on the net was that auto id (IDENTITY) is managed by database and never fetched in Entity until unless you commit the row or manually retrieve the info from database.




回答2:


The problem is you are using IDENTITY id generation. IDENTITY id generation cannot do preallocation as they require the INSERT to generate the id. TABLE and SEQUENCE id generation support preallocation, and I would always recommend usage of these, and never using IDENTITY because of this issue and because of performance.

You can trigger the id to be generated when using IDENTITY id generation by calling flush().




回答3:


just simply do this :

public void create(T entity) {
   getEntityManager().persist(entity);
   getEntityManager().flush();
   getEntityManager().refresh(entity);
}

After refreshing the entity you have the ID field with proper value.



来源:https://stackoverflow.com/questions/4870863/why-jpa-persist-does-not-generated-auto-increment-primary-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!