简体   繁体   中英

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)?

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() ; 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. 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. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. 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.

Source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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