【问题标题】:Why JPA persist() does not generated auto-increment primary ID?为什么 JPA persist() 不生成自增主 ID?
【发布时间】:2011-06-19 17:50:09
【问题描述】:

我正在使用 JPA toplink-essential 和 SQL Server 2008

我的目标是获取要插入到表中的数据的自增主键值。我知道在 JDBC 中,有类似 getInsertedId() 的方法可以为您提供自动递增主 ID 的 ID(但那是在插入语句执行之后)

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

【问题讨论】:

  • 如果我提交,我可以获得 id:em.getTransaction().commit() 但是没有办法通过persist 获得 id ???嗯
  • 您的代码应该可以按预期工作。我对其进行了测试,并且在提交之前或者如果我随后回滚,我将获得 id。奇怪的是它没有。
  • 如果 tableId 是 int 而不是 Integer 会有什么不同吗?
  • 我将类型从“Integer”切换为“int”,现在 parent.getTableId() 返回 0(使用 @GeneratedValue.SEQUENCE)虽然它不应该为 0,但不知道为什么。跨度>
  • 它是int类型的默认值,与数据库或JPA无关。

标签: java jpa toplink-essentials


【解决方案1】:

问题是您正在使用 IDENTITY id 生成。 IDENTITY id 生成不能进行预分配,因为它们需要 INSERT 来生成 id。 TABLE 和 SEQUENCE id 生成支持预分配,我总是建议使用这些,并且因为这个问题和性能,从不使用 IDENTITY。

在使用IDENTITY id生成时可以通过调用flush()来触发生成id。

【讨论】:

  • 嗯序列对我不起作用。我将实体类中的注释更改为:@Id @SequenceGenerator(name="seq", sequenceName="seq") @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")
  • 然后在 em.persist(myBean); int insertId = myBean.getId();这个 getId() 正在返回 null...我做错了吗?
  • 那是时间问题。当您尝试获取 id 值时,JPA 没有插入数据。您必须刷新以使他开始对数据库进行修改。之后你就有了身份证。更好的是,当您调用 getId() 时,JPA 会对数据库进行修改。
【解决方案2】:

只需这样做:

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

刷新实体后,您的 ID 字段具有正确的值。

【讨论】:

【解决方案3】:

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

我在网上找到的原因是 auto id (IDENTITY) 是由数据库管理的,除非你提交行或手动从数据库中检索信息,否则永远不会在 Entity 中获取。

【讨论】:

  • 你的意思是因为SQL Server 2008,我们不能使用@GeneratedValue.Sequence or Table or Identity ???我想我必须先刷新(插入对 db 的调用以获取生成的 id),但如果我可以获得主 id,我的目标是没有插入调用。
  • 你可能是对的,文档似乎没有列出 SQL Server 支持 SEQUENCE 对象....“序列对象使用特殊的数据库对象来生成 id。序列对象仅在某些数据库中支持,例如 Oracle、DB2 和 Postgres。” en.wikibooks.org/wiki/Java_Persistence/…
  • 标记为答案,SQL Server 不支持 SEQUENCE
猜你喜欢
  • 2012-04-01
  • 2012-06-18
  • 2010-11-07
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
  • 2010-12-21
  • 2014-09-22
  • 1970-01-01
相关资源
最近更新 更多