簡體   English   中英

為什么JPA persist()不會生成自動增量主ID?

[英]Why JPA persist() does not generated auto-increment primary ID?

我正在使用JPA toplink-essentialSQL Server 2008

我的目標是獲取將要插入表中的數據的自動增量主鍵值。 我知道在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 :(

問題是你正在使用IDENTITY id生成。 IDENTITY id生成無法進行預分配,因為它們需要INSERT來生成id。 TABLE和SEQUENCE id生成支持預分配,我總是建議使用這些,並且由於這個問題和性能,我從不使用IDENTITY。

您可以通過調用flush()來觸發在生成IDENTITY id時生成的id。

只需這樣做:

public void create(T entity) {
   getEntityManager().persist(entity);
   getEntityManager().flush();
   getEntityManager().refresh(entity);
}

刷新實體后,您將獲得具有適當值的ID字段。

我們也使用SQL Server 2008,它從來沒有為我工作,所以我總是執行單獨的查詢"SELECT @@IDENTY"來獲取插入的ID。

我在網上找到的原因是自動ID(IDENTITY)由數據庫管理,除非您提交行或手動從數據庫中檢索信息,否則永遠不會在實體中提取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM