为什么JPA persist()不会生成自动增量主ID? [英] Why JPA persist() does not generated auto-increment primary ID?

查看:101
本文介绍了为什么JPA persist()不会生成自动增量主ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我的目标是获得自动-increment将要插入表中的数据的主键值。我知道在JDBC中,有getInsertedId()方法,它给你自动增加主id的id(但是在执行insert语句之后)

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)

在JPA中,我发现 @GenratedValue注释可以做到这一点。

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;






现在,如果我运行下面的代码,它应该给出我自动递增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 :(


推荐答案

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

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.

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

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.

这篇关于为什么JPA persist()不会生成自动增量主ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆