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