出于某些好的原因,我进行了Spring Data JPA本地插入。
查询以正确的方式执行。
但是我需要的是由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);
整数返回值仅提供插入记录的数量(1)。但是我需要新的ID。我不想通过另一个数据库查询在插入后查询它。因为如果我必须这样做,整个本地插入就会过时。
有人知道答案/有人有替代方法吗? 谢谢! 问候 Thomas
编辑: 我使用本机插入来避免加载整个工作申请记录,这是很多无用数据中的持久化数据的方式与实体管理器。
相反,我使用本地插入数据。
无论如何,您关于从插入语句返回数据的提示非常酷。 我试了一下,它起作用了。非常感谢您! 我最终采用了这个解决方案:
/**
* 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);
RETURNING *
,而只删除@Modifying
就足够了。 - Kalana Dananjaya