如何使用JPA获取最后一个持久化实体的Id [英] How to get Id of last persisted entity using JPA

查看:239
本文介绍了如何使用JPA获取最后一个持久化实体的Id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种智能且易读的方法来使用 JPA 获取持久化实体的ID。 id是 Integer

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. 不使用 GeneratedValue 策略。这需要在持久化之前寻找一个免费的ID,然后将其放入要保留的实体中:繁琐但有效。

  2. 使用 GeneratedValue 策略。持久性提供程序将负责id生成。这看起来更聪明,但如何获得ID?

  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?

请参阅下面的解决方案2

See below for solution 2

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

这会输出一个空ID!

This prints a null id!

有什么建议吗?我正在使用MySql,EclipseLink,但需要一个可移植的解决方案。

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

推荐答案

persist不保证生成ID。保证ID仅在刷新时生成。因此,如果您在事务结束之前确实需要ID(并且实体管理器被刷新),请明确调用flush()以获取ID:

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());

这篇关于如何使用JPA获取最后一个持久化实体的Id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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