java 集群中 h2 和 MySQL 的休眠 ID 生成器 AUTO_INCREMENT

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11248094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:23:43  来源:igfitidea点击:

hibernate id generator AUTO_INCREMENT at h2 and MySQL in a cluster

javahibernatecluster-computingauto-increment

提问by Poni

For testing I'm using the H2 database.

为了测试,我使用了H2 数据库

For production it's MySQL.

对于生产,它是MySQL

I understrand that both support AUTO_INCREMENT(mysql/ h2), but it seems like Hibernate doesn't work this way.

我了解两者都支持AUTO_INCREMENTmysql/ h2),但似乎 Hibernate 不能以这种方式工作。

identityis supported for MySQL. Fine.
What about H2? Should I write my own generator or...? (using the org.hibernate.id.IdentifierGeneratorinterface as the doc says).

identityMySQL 支持。美好的。
H2呢?我应该编写自己的生成器还是...?(使用org.hibernate.id.IdentifierGenerator文档所说的界面)。

I must have a nice clean & quick way to get an ID (of type longby the way) from the database itself because the application is in a cluster(i.e several servers INSERTinto the database at once)... that's why incrementis definitely not for me.

我必须有一个很好的干净和快速的方法来long从数据库本身获取 ID(顺便说一下类型),因为应用程序在一个集群中(即多个服务器INSERT一次进入数据库)......这就是为什么increment绝对不适合我。

Thanks!

谢谢!

回答by Alex Barnes

You should just annotate your id property which needs the generated value with @GeneratedValue. This will automatically select the appropriate generation strategy for the database you're using. See GenerationType.AUTOfor more details.

您应该只用@GeneratedValue 注释需要生成值的 id 属性。这将自动为您使用的数据库选择适当的生成策略。有关GenerationType.AUTO更多详细信息,请参阅。

Your property will look like this:

您的属性将如下所示:

@Id
@GeneratedValue
private long id;

回答by Johanna

Use the native generator, for example

例如,使用本机生成器

<id name="id" type="int">
    <column name="id_column" />
    <generator class="native" >
        <param name="sequence">id_column_sequence</param>
    </generator>            
</id>

The generator with the class nativeuses the best generation strategy for the database. In the case of MySql this is auto_increment, in the case of Oracle this is a sequence (and for H2 it also should be a sequence, but I've never tried, because I don't use H2). The generator parameter sequenceonly is used if it is useful, i. e. for MySql databases the parameter is ignored, and for Oracle it is used.

具有该类的生成器native使用数据库的最佳生成策略。在 MySql 的情况下,这是 auto_increment,在 Oracle 的情况下,这是一个序列(对于 H2,它也应该是一个序列,但我从未尝试过,因为我不使用 H2)。生成器参数sequence仅在有用时才使用,即对于 MySql 数据库该参数将被忽略,而对于 Oracle 则使用它。

In that way you can use the same mapping file for different database types (at least as long as the table and column names are the same).

通过这种方式,您可以对不同的数据库类型使用相同的映射文件(至少只要表名和列名相同)。