简体   繁体   English

如何使用JPA获取最后一个持久化实体的Id

[英]How to get Id of last persisted entity using JPA

I am looking a smart and easily readable way to get the id of a persisted entity using JPA . 我正在寻找一种智能且易读的方法来获取使用JPA的持久化实体的id。 The id is an Integer . id是一个Integer

One could think of the following solutions: 人们可以想到以下解决方案:

  1. Without using GeneratedValue strategy. 不使用GeneratedValue策略。 This requires looking for a free id before persisting, then putting it into the entity to be persisted: cumbersome, but works. 这需要在持久化之前寻找一个免费的id,然后将它放入要保留的实体中:繁琐,但有效。
  2. With a GeneratedValue strategy. 使用GeneratedValue策略。 The persistence provider will take care of the id generation. 持久性提供程序将负责id生成。 This looks smarter, but how to get the id? 这看起来更聪明,但如何获得身份证?

See below for solution 2 请参阅下面的解决方案2

MyEntity en = new MyEntity();
en.setName("My name");
em.persist(en);
System.out.println(en.getId());

This prints a null id! 这打印出一个空id!

Any suggestions? 有什么建议? I am using MySql, EclipseLink, but need a portable solution. 我正在使用MySql,EclipseLink,但需要一个可移植的解决方案。

persist is not guaranteed to generate the ID. persist不保证生成ID。 The ID is guaranteed to be generated at flush time only. 保证ID仅在刷新时生成。 So if you really need the ID before the transaction ends (and the entity manager is thus flushed), call flush() explicitely to get the ID: 因此,如果在事务结束之前确实需要ID(并且实体管理器因此被刷新),则明确调用flush()以获取ID:

MyEntity en = new MyEntity();
en.setName("My name");
em.persist(en);
em.flush();
System.out.println(en.getId());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM