本地插入后如何获取新的记录ID

Tho*_*ang 5 hibernate jpa spring-data-jpa

出于一些很好的原因,我做了一个 spring 数据 jpa 本机插入。
查询以正确的方式执行。
但我需要的是新生成的表 id 由nextval('hibernate_sequence')

有没有办法获得这个id?

这是我的查询:

/**
 * Inserts a new file attachment.
 * This is useful and maybe better suitable, because one may not want to load the whole
 * job offer to fullfill the JobOffer -> FileAttachment OneToMany Relation
 *
 * @param file       a given file
 * @param fileName   a given file name
 * @param jobOfferId a given job offer id
 * @return int the new id
 */
@Modifying
@Query(value = "insert into fileattachment(fileattachmentid, file, filename, joboffer_jobofferid) values (nextval('hibernate_sequence'), ?1, ?2, ?3);", nativeQuery = true)
int insertFileAttachment(String file, String fileName, long jobOfferId);
Run Code Online (Sandbox Code Playgroud)

int 返回值仅给出插入记录的数量 (1)。
但我需要新的 ID。
我不想在另一个数据库查询插入后查询它。因为如果我必须这样做,整个本机插入都会过时。

有人知道答案/有人有其他提示吗?
谢谢!
亲切的问候
托马斯

编辑
我使用本机插入来避免加载整个 joboffer 记录,这是很多无用的数据,只是为了以实体管理器的方式持久化数据。

相反,我插入了本机数据。

无论如何,您从插入语句返回数据的提示非常酷。
我正在尝试,它正在工作。非常非常感谢你!
我最终得到了这个解决方案:

/**
 * Inserts a new file attachment.
 * This is useful and maybe better suitable, because one may not want to load the whole
 * job offer to fullfill the JobOffer -> FileAttachment OneToMany Relation
 *
 * @param file       a given file
 * @param fileName   a given file name
 * @param jobOfferId a given job offer id
 * @return int the new id
 */
@Query(value = "insert into fileattachment(fileattachmentid, file, filename, joboffer_jobofferid) values (nextval('hibernate_sequence'), ?1, ?2, ?3) returning fileattachmentid;", nativeQuery = true)
long insertFileAttachment(String file, String fileName, long jobOfferId);
Run Code Online (Sandbox Code Playgroud)

cri*_*zis 2

有办法得到这个id吗?

并非没有查询数据库就没有。除非您愿意使用普通的 JDBC。

如果您FileAttachment@ManyToOne JobOffer offer,为什么不执行以下操作:

FileAttachment attachment = new FileAttachment(file, fileName);
attachment.setJobOffer(entityManager.getReference(JobOffer.class, jobOfferId));
entityManager.persist(attachment);
entityManager.flush();
return attachment.getId();
Run Code Online (Sandbox Code Playgroud)

这样,您将避免加载 的整个状态JobOffer。如果关系是单向的,恐怕你将不得不检索整个JobOffer.

或者,如果您确实必须使用本机INSERT,请考虑在数据库中定义一个存储过程,该存储过程将插入数据并返回自动生成的 id(请参阅此处)。

此外,某些数据库(例如 PostgreSQL)允许从INSERT语句 ( INSERT (..) INTO FILEATTACHMENT RETURNING ID) 返回数据。您可能需要删除@Modifying注释,因为插入的 id 最终会出现在查询的结果集中。你没有提到你正在使用哪个数据库,但语法看起来像 Postgres,这就是我选择这个例子的原因。如果您使用其他数据库,请查阅文档,也许有类似的功能。

但是,我仍然建议不要INSERT在 JPA 应用程序中使用本机语句。很多东西都会坏掉。我怀疑您尝试实现的方法不是更大工作单元的一部分,但如果是这样,我会非常小心。