【问题标题】:How to get the ID (PRIMARY KEY) from an entity object after commit transaction?提交事务后如何从实体对象中获取 ID(主键)?
【发布时间】:2023-04-01 20:45:01
【问题描述】:

在我持久化一个对象并像这样提交之后:

        Version version = new Version();
        version.setVersion(getNext(this.version));
        version.setProjectID(projectID);
        em.persist(version);
        em.getTransaction().commit();

我想通过这个代码行获取 ID(Primary Key):

Object id = factory.getPersistenceUnitUtil().getIdentifier(version);

我可以得到VersionProjectID,但IDnull。 ID 是自动生成的,但仍返回 null。我试图在我的实体类中实现@GeneratedValue(strategy=GenerationType.IDENTITY),但没有任何改变。有什么解决办法吗?

编辑更多代码

版本实体:这是使用 EmbededId

    @Entity
    @NamedQuery(name="Version.findAll", query="SELECT v FROM Version v")
    @Table(name="Version")
    public class Version implements Serializable {    

    @EmbeddedId
    @GeneratedValue(strategy=GenerationType.SEQUENCE)
    private VersionPK id;

    @Column(name="Version")
    private String version;

    @Column(name="ProjectID")
    private int projectID;

可嵌入类:

    @Embeddable
    public class VersionPK implements Serializable {
    //default serial version id, required for serializable classes.
    private static final long serialVersionUID = 1L;

    @Column(name="ID")
    private int id;

    public VersionPK() {
    }

【问题讨论】:

  • 我不太确定我是否理解正确,但您可以看看 JPA2 中的 @id 注释。也许这可以解决您的问题。
  • 也许向人们展示你的实际课程可能会有所帮助?
  • 我认为问题在于该实体对象无法从数据库中获取自动生成的 ID。方法 version.getId() 总是返回 null 但 version.getVersionversion.getProjectID 运行良好。

标签: java jpa eclipselink jpa-2.0


【解决方案1】:

你必须在提交后使用flush()才能获得id

em.persist(version);
em.getTransaction().commit();
em.flush();

然后只需使用 getter 获得 id:

Object id = version.getId();//getId() is the getter of the id in your entity.

See the answer here.

【讨论】:

  • flush() 提交后没有意义,因为如果没有事务处于活动状态,它将抛出 TransactionRequiredException,根据 javadoc。
  • 在这种情况下,确保您的交易不是null会更安全
  • null 和它有什么关系?如果您提交 txn,则没有交易,也就是您的代码
  • 这就是为什么你必须在提交之前测试你的事务不为空。
  • 我说在提交后调用刷新是错误的。 flush 用于事务中
猜你喜欢
  • 1970-01-01
  • 2011-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
  • 2012-12-30
  • 2022-12-05
  • 1970-01-01
相关资源
最近更新 更多