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

前端 未结 3 1974
长发绾君心
长发绾君心 2021-01-05 07:42

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 t

相关标签:
3条回答
  • 2021-01-05 08:00

    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.

    0 讨论(0)
  • 2021-01-05 08:11

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

    0 讨论(0)
  • 2021-01-05 08:22

    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.

    0 讨论(0)
提交回复
热议问题