如何在JPA中使用本地查询插入后获取返回的ID?

10

我在JPA中有以下代码,用于使用本地查询插入后返回自动生成的ID:

Query q = em.createNativeQuery("insert into .... returning ID", Long.class);
q.executeUpdate();

然而,我遇到了以下错误:
A result was returned when none was expected
1个回答

13

好的,这很简单。我刚刚使用了q.getSingleResults(),并且它运行得很好!

Query q = em.createNativeQuery(sql);
BigInteger biid = (BigInteger) q.getSingleResult();
long id = biid.longValue();

1
在MySql中,这个不起作用,你会得到下一个错误。java.sql.SQLException: 无法使用executeQuery()发出数据操作语句。 - TheGabiRod
3
在MySQL中,我使用了以下代码:long lastId = ((BigInteger) entityManager.get().createNativeQuery("SELECT LAST_INSERT_ID()").getSingleResult()).longValue();请注意,这是一个代码片段,它的作用是获取最后插入的记录的ID值。 - Austin Cary
2
在MSSQL中,我在这一行代码BigInteger biid = (BigInteger) q.getSingleResult();处遇到了"org.hibernate.exception.GenericJDBCException: could not extract ResultSet"的错误。 - Hikaru Shindo
似乎真的取决于您使用的数据库。在我的情况下,使用Oracle,getSingleResult也会抛出“无法提取ResultSet”的异常。 - mgueydan
@mgueydan 我只在postgres上测试过。你在插入语句中返回ID吗?我认为在Oracle中这并不那么简单。在Oracle中,您需要将ID保存到变量中,然后从dual中选择它。(insert into ... returning ID into :var; select :var from dual)。但我不确定这是否适用于JPA。 - fareed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接