为什么JPA persist()不会生成自动增加主ID?

问题描述:

我使用JPA的TopLink必要SQL Server 2008中为什么JPA persist()不会生成自动增加主ID?

我的目标是获取将要插入到表中的数据的自动增量主键值。我知道在JDBC,有getInsertedId()之类的方法,让你自动增量的主ID的ID(但尽管执行INSERT语句之后的)

在JPA中,我发现了@GenratedValue annotation可以做的伎俩。

@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 :(
+0

我可以得到id如果我提交:em.getTransaction()。commit()但没有办法获得id已经持续??? hmm – 2011-02-02 05:39:31

+0

您的代码应该按照您的预期工作。我测试了它,并在提交之前得到了id,或者如果我回滚了。奇怪的是,它没有。 – Joel 2011-02-02 11:02:42

+0

如果tableId是一个int而不是Integer,它会有什么区别吗? – Joel 2011-02-02 11:05:11

我们还利用SQL Server 2008和它从来没有为我工作,所以我总是执行单独的查询"SELECT @@IDENTY"获取插入的ID。

我在网上发现的原因是自动ID(IDENTITY)由数据库管理,并且从未在实体中获取,除非您提交该行或手动从数据库检索信息。

问题是您正在使用IDENTITY ID代。 IDENTITY ID生成不能进行预分配,因为它们需要INSERT生成ID。 TABLE和SEQUENCE ID生成支持预分配,我总是会推荐使用这些,并且从不使用IDENTITY,因为这个问题以及性能。

您可以通过调用flush()来触发要在生成IDENTITY ID时生成的id。

只是单纯地做到这一点:

​​

刷新你有正确的价值ID字段中的实体之后。