Why JPA persist() does not generated auto-increment primary ID?
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
ca开发者_如何学JAVAn 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 :(
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().
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.
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.
精彩评论