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

查看:58
本文介绍了如何使用 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

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天全站免登陆