如何在本机插入后获取新记录ID

时间:2018-04-27 08:20:00

标签: hibernate jpa spring-data-jpa

出于某些原因,我做了一个spring data jpa native insert 查询以正确的方式执行 但我需要的是由nextval('hibernate_sequence')

生成的新生成的表ID

有没有办法获得此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);

int返回值只给出插入记录的数量(1) 但我需要新的身份证 我不想在插入另一个数据库查询后查询它。因为如果必须,整个原生插入都会过时。

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

修改
我使用本机插入来避免加载整个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);

1 个答案:

答案 0 :(得分:1)

  

有没有办法获得此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();

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

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

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

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