简体   繁体   中英

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 . The id is an Integer .

One could think of the following solutions:

  1. Without using GeneratedValue strategy. This requires looking for a free id before persisting, then putting it into the entity to be persisted: cumbersome, but works.
  2. With a GeneratedValue strategy. The persistence provider will take care of the id generation. This looks smarter, but how to get the id?

See below for solution 2

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

This prints a null id!

Any suggestions? I am using MySql, EclipseLink, but need a portable solution.

persist is not guaranteed to generate the ID. The ID is guaranteed to be generated at flush time only. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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