如何在本机查询插入后在JPA中返回ID

时间:2017-07-17 21:52:41

标签: postgresql hibernate jpa

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

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

但是,我收到以下错误:

A result was returned when none was expected

1 个答案:

答案 0 :(得分:4)

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

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