简体   繁体   English

休眠如何在 session.save(object) 上获取新插入的记录主键

[英]How is hibernate getting the newly inserted record primary key on session.save(object)

I know that we can get the primary key of the newly inserted record with object.getId() when we do hibernate session.save(object) .我知道当我们执行 hibernate session.save(object)时,我们可以使用object.getId()获取新插入记录的主键。 I want to understand how is hibernate getting this id.我想了解 hibernate 是如何获得这个 id 的。 I want to achieve the same using a plain SQL query instead of using hibernate.我想使用普通的 SQL 查询而不是使用休眠来实现相同的目的。

DB Server is MySQL.数据库服务器是 MySQL。

I agree with @JB Nizet about generation: it depends on your annotation and, in any case, the id is assigned to your bean at the commit phase not before so the persistent provider must read the new generated id from database.我同意@JB Nizet 关于生成:这取决于您的注释,并且无论如何,id 在提交阶段分配给您的 bean,而不是在此之前,因此持久提供程序必须从数据库中读取新生成的 id。

Many databases offer a mechanism for doing what is required.许多数据库提供了一种机制来执行所需的操作。 MySQL provides a function LAST_INSERT_ID() . MySQL 提供了一个函数LAST_INSERT_ID() More details here or there更多细节在这里那里

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

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