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