【发布时间】:2015-08-10 00:07:44
【问题描述】:
在我的应用程序中,我正在生成一个 SQL-INSERT。此插入将作为 JPA 原生查询 (Hibernate) 执行,并在我们的 SQL Server 中自动生成一个新的标识值。
如何接收生成的身份值?
我想避免对@@IDENTITY 进行第二次选择,因为第二个用户可能同时插入了一些内容,从而导致错误的结果。
(见Getting generated identifier for JPA native insert query)
使用@@IDENTITY 的代码如下所示:
Query statementInsert = entityManager.createNativeQuery("INSERT INTO x(colum1, column2) VALUES (:value1, :value2)");
// setting parameters...
statementInsert.executeUpdate();
Query statmentSelectId = entityManager.createNativeQuery("SELECT @@IDENTITY");
int generatedId = ((BigDecimal) statmentSelectId.getSingleResult()).intValueExact();
我更愿意将SELECT SCOPE_IDENTITY() 放在我的INSERT-Statement 后面(见
How to get Identity value from SQL server after insert record)。这需要对 JPA 原生查询进行某种“批量执行”。
我梦想着这样的事情:
Query statementInsertAndSelectId = entityManager.createNativeQuery("INSERT INTO x(colum1, column2) VALUES (:value1, :value2); SELECT SCOPE_IDENTITY();");
// setting parameters...
// ?????????
int generatedId = ((BigDecimal) statementInsert.getSingleResult()); // not working, JPA complains about "No ResultSet"
在我的项目中无法使用“条件生成器”或“命名查询”。
【问题讨论】:
-
不能使用存储过程吗?
-
也许您可以在插入中使用 OUTPUT 子句 - 如果您使用的是 SQLServer (technet.microsoft.com/en-us/library/ms177564.aspx)
标签: java sql-server hibernate jpa