【问题标题】:How to get returning ID in JPA after native query insert本地查询插入后如何在 JPA 中获取返回 ID
【发布时间】:2017-12-22 13:57:02
【问题描述】:

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

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

但是,我收到以下错误:

A result was returned when none was expected

【问题讨论】:

    标签: postgresql hibernate jpa


    【解决方案1】:

    好的,这很容易。我刚刚使用了 q.getSingleResults() 并且效果很好!

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

    【讨论】:

    • 在MySql这个dosen工作,你会得到下一个错误。 java.sql.SQLException: 无法使用 executeQuery() 发出数据操作语句。
    • 在 MySQL 中我使用了:long lastId = ((BigInteger) entityManager.get().createNativeQuery("SELECT LAST_INSERT_ID()").getSingleResult()).longValue();
    • 在 MSSQL 中,我在 BigInteger biid = (BigInteger) q.getSingleResult(); 行得到“org.hibernate.exception.GenericJDBCException: could not extract ResultSet”
    • 它似乎真的取决于您使用的数据库。在我的情况下,使用 Oracle,它 getSingleResult 也会抛出“无法提取 ResultSet”。
    • @mgueydan 我只用 postgres 测试过它。您是否在插入语句中返回 ID?我不认为它在甲骨文中那么直截了当。在 Oracle 中,您需要将 id 保存到变量中,然后从对偶中选择它。 (插入...将ID返回到:var;从双重中选择:var。但我不确定这在JPA中是否有效
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2017-02-08
    • 2017-03-26
    • 2020-06-05
    相关资源
    最近更新 更多