java - Hibernate 序列生成器因为多个实体共享而感到困惑

标签 java mysql hibernate

我的类(class)使用像这样的ID

@Id @Generated(GenerationTime.INSERT) @GeneratedValue private Integer id;

这非常适用于 H2(支持序列),并通过创建帮助表 hibernate_sequence 为 MySql 进行解释。使用this answer ,一切看起来都是我想要的方式,尤其是对所有表使用单个序列。

有一件事似乎是错误的:助 watch 中有多行。我的 id@MappedSuperclass 中声明,并且在初始化期间,对于每个具体类执行以下行:

insert into hibernate_sequence values ( 1 )

这显然是错误的:每个表都有一行,每行都包含相同的值(最初是一个;当更改时,它们都以相同的方式更改,因为 SQL 是 update hibernate_sequence set next_val=? where next_val=?,因此它以相同的方式影响所有行)。

它是无害的,但我想知道:这是一个错误还是我做错了什么?

最佳答案

如果你想让它起作用,你现在需要使用其他策略:

@GenericGenerator(
        name = "table_generator",
        strategy = "org.hibernate.id.enhanced.TableGenerator"
)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "table_generator")

关于org.hibernate.id.enhanced.SequenceStyleGenerator:

我认为 hibernate 如何初始化共享的单行序列表存在问题。

对于 hibernare 5.0.6.Final 问题的根源在于 org.hibernate.boot.internal.InFlightMetadataCollectorImpl 类 在

private void processExportableProducers(MetadataBuildingContext buildingContext) {
    // for now we only handle id generators as ExportableProducers

    final Dialect dialect = getDatabase().getJdbcEnvironment().getDialect();
    final String defaultCatalog = extractName( getDatabase().getDefaultNamespace().getName().getCatalog(), dialect );
    final String defaultSchema = extractName( getDatabase().getDefaultNamespace().getName().getSchema(), dialect );

    for ( PersistentClass entityBinding : entityBindingMap.values() ) {
        if ( entityBinding.isInherited() ) {
            continue;
        }

        // ***************************************************************************
        // For Instance, it does not filter out the same entityBinding.getIdentifier()
        // and make initialization multiple time
        // ***************************************************************************
        handleIdentifierValueBinding(
                entityBinding.getIdentifier(),
                dialect,
                defaultCatalog,
                defaultSchema,
                (RootClass) entityBinding
        );
    }

    for ( Collection collection : collectionBindingMap.values() ) {
        if ( !IdentifierCollection.class.isInstance( collection ) ) {
            continue;
        }

        handleIdentifierValueBinding(
                ( (IdentifierCollection) collection ).getIdentifier(),
                dialect,
                defaultCatalog,
                defaultSchema,
                null
        );
    }
}

关于java - Hibernate 序列生成器因为多个实体共享而感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34596464/

相关文章:

Java FX 2 CSS 伪类

java - 将 XML 对象持久保存到数据库中的现代方法是什么?

java - Hibernate:实体映射中的重复列

java - IdentityHashMap 的默认大小不正确?为什么

java - 从 float 中恢复原始数字

mysql - 使用 JSON 中的 Feeds 模块导入时,13 位数字会得到指数格式

sql - MySQL 从另一个具有重复 ID/数据的表中获取数据

mysql - 与 "foo.bar"匹配(带有句号/句号)

hibernate - 想用 HQL 只获取 5 条记录

java - 用于事务管理的 Spring + HibernateTemplate + AOP 不起作用