我正在使用JPA toplink-essential和SQL Server 2008
我的目标是获取将要插入表中的数据的自动增量主键值.我知道在JDBC中,有getInsertedId()方法,它给你自动增加主id的id(但是在执行insert语句之后)
在JPA中,我发现@GenratedValue注释可以做到这一点.
@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;
现在,如果我运行下面的代码,它应该给我自动增加的id但它返回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 :(