Hibernate: How does native identifier generation s

2019-09-01 02:04发布

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?

1条回答
对你真心纯属浪费
2楼-- · 2019-09-01 02:26

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.

查看更多
登录 后发表回答