Hibernate:本地标识符生成策略如何工作 [英] Hibernate: How does native identifier generation strategy work

查看:159
本文介绍了Hibernate:本地标识符生成策略如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hibernate有一个名为 native 的标识符生成策略,它选择 identity sequence code>或 hilo ,这取决于底层数据库的功能。我使用了 hibernate.hbm2ddl.auto = update 的MySQL,它为 id BIGINT(20)NOT NULL AUTO_INCREMENT c $ c $> b













$了解Hibernate在使用 SchemaExport 工具时如何选择 AUTO_INCREMENT 。是 AUTO_INCREMENT MySQL的默认主键生成策略?



有人可以帮我理解吗?

解决方案

Hibernate在纯模式中选择密钥生成机制时,会尝试选择数据库中可用的最佳机制。在MySQL的情况下,自动递增是可用的,Hibernate使用它来代替序列,因为自动递增机制略好一些,尽管序列也可以正常工作。



为什么最好是在一个JDBC准备语句(例如插入)中可以执行插入操作并检索生成的密钥而不查询数据库 - 请参阅 here 获取更多详细信息。



<在序列的情况下,Hibernate必须先在某个时间点调用序列,然后使用公式中使用的值或结果来填充插入键,然后发出插入。

自动增量省去了额外的往返数据库以增加序列的数量,这就是Hibernate喜欢MySQL的原因。

Hibernate has an identifier generation strategy called native that selects identity, sequence or hilo depending upon the capabilities of the underlying database. I used MySQL with hibernate.hbm2ddl.auto=update which generated id BIGINT(20) NOT NULL AUTO_INCREMENT for id property of Long Java data type.

I am trying to understand how did Hibernate choose AUTO_INCREMENT when it used SchemaExport tool. Is AUTO_INCREMENT the default primary key generation strategy for MySQL?

Could somebody help me understand it?

解决方案

Hibernate when selecting the key generation mechanism in native mode, will try to choose the best mechanism available in the database. In the case of MySQL, auto increment is available and Hibernate uses it instead of a sequence, because the auto increment mechanism is slightly better altough sequences also work fine.

The reason why it's better is that it's possible in one single JDBC prepared statement, for example an insert, to do an insert AND retrieve the generated key without querying the database - see here for further details.

In the case of sequences, Hibernate has to first call the sequence at some point and then use the value or the result of it's use in a formula to populate the insert key and then issue the insert.

The autoincrement spares this extra roundtrip to the database needed to increment the sequence, and that is the reason why Hibernate prefers it in the case of MySQL.

这篇关于Hibernate:本地标识符生成策略如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆