gpt4 book ai didi

hibernate - 序列问题为什么在使用 hbm2ddl 生成架构时两个实体共享相同的序列?

转载 作者:行者123 更新时间:2023-12-02 22:29:35 25 4
gpt4 key购买 nike

我在基于 hibernate 的应用程序中使用hbm2ddl来生成数据库架构。 hibernate.hbm2ddl.auto 属性的值为 create-drop

我正在为我的 POJO 类使用 @Entity 注释。

@Entity 
public class testTable1 {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
Long id;
}

@Entity
public class testTable2 {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
Long id;
}

但是,在执行代码时,我不断获得不断递增的 Id 值。例如对于 2 个表,Id(即 Prim Key)应以 1 开头。但是在表 1 中插入记录后,序列将从 表 2 的下一个值开始。表 2 应该从 1 重新开始。我尝试了GenerationType.SEQUENCEGenerationType.AUTO。没有任何效果:-(

最佳答案

当 JPA 规范未提供生成器时,您正在使用 hibernate 默认提供的全局序列生成器。要拥有私有(private)生成器,您应该使用注释 @SequenceGenerator 声明私有(private)生成器,并设置 @GenerateValue 注释的 generator 属性

摘自javadoc

@GeneratedValue
(Optional) The name of the primary key generator to use as specified in the SequenceGenerator or TableGenerator annotation.

Defaults to the id generator supplied by persistence provider.

SequenceGenerator
This annotation defines a primary key generator that may be referenced by name when a generator element is specified for the GeneratedValue annotation. A sequence generator may be specified on the entity class or on the primary key field or property. The scope of the generator name is global to the persistence unit (across all generator types).

Example:

@SequenceGenerator(name="EMP_SEQ", sequenceName="private_sequence")

Hibernate 建议新项目使用 hibernate.id.new_generator_mappings=true,因为新的生成器更高效且更接近 JPA 2 规范语义

Section 1.3. Properties
2.2.3. Mapping identifier properties

完整示例

@Entity
@SequenceGenerator(name="PRIVATE_SEQ", sequenceName="private_sequence")
public class test {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="PRIVATE_SEQ")
Long id;
}

关于hibernate - 序列问题为什么在使用 hbm2ddl 生成架构时两个实体共享相同的序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6878093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com