简体   繁体   English

Hibernate会话-如何使用原始SQL插入并获取生成的ID?

[英]Hibernate session - how to insert with raw sql and get the generated id?

Using the hibernate session and MySQL, is it possible to insert a row in the database with raw SQL and then get the generated id, within the same transaction (avoiding concurrency issues)? 使用休眠会话和MySQL,是否可以在同一事务中通过原始SQL在数据库中插入一行,然后获取生成的ID(避免并发问题)?

Table: 表:

CREATE TABLE EMPLOYEE (ID int(11) NOT NULL, NAME varchar(50) NOT NULL, PRIMARY KEY (ID));

What I'm doing today: 我今天在做什么:

getSession().createSQLQuery("INSERT INTO EMPLOYEE (NAME) VALUES ('JOHN')").executeUpdate();

Thanks 谢谢

Should be able to use LAST_INSERT_ID() ; 应该能够使用LAST_INSERT_ID() ; it's determined per-connection, so as long as you call it immediately after the insert, there's no race condition. 它是按连接确定的,因此,只要您在插入后立即调用它,就不会出现争用情况。

The ID that was generated is maintained in the server on a per-connection basis. 生成的ID在每个连接的服务器中维护。 This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. 这意味着函数返回给定客户端的值是针对该客户端影响AUTO_INCREMENT列的最新语句生成的第一个AUTO_INCREMENT值。 This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. 即使其他客户端生成自己的AUTO_INCREMENT值,该值也不会受到其他客户端的影响。 This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions. 此行为可确保每个客户端都可以检索自己的ID,而不必担心其他客户端的活动,也不需要锁或事务。

Source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM