gpt4 book ai didi

java - JPA @TableGenerator 在多个实体之间共享

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:27:24 26 4
gpt4 key购买 nike

我有一个带有@Id 和@TableGenerator 的“狗”实体

...
@TableGenerator(table = "seq", name = "dog_gen", pkColumnName = "seq_name", valueColumnName="seq_val")
@Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "dog_gen")
private Long id;
...

有没有办法在其他实体中重用相同的表生成器 (dog_gen)?我想在两个独立的实体中保持相同的 id 序列,比如

狗=1,狗=2,狗=3,猫=4,猫=5,狗=6等等……

两个实体不共享一个公共(public)父类(super class)来实现某种带有 id 属性的继承。

如果我在我的 cat 实体上添加 @GeneratedValue( generator="dog_gen") ,省略 @TableGenerator 声明会抛出一个异常,指出它在启动上下文时找不到生成器。

Caused by: org.hibernate.AnnotationException: Unknown Id.generator: dog_gen
at org.hibernate.cfg.BinderHelper.makeIdGenerator(BinderHelper.java:413)
at org.hibernate.cfg.AnnotationBinder.bindId(AnnotationBinder.java:1795)
at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1229)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:733)
at org.hibernate.cfg.AnnotationConfiguration.processArtifactsOfType(AnnotationConfiguration.java:498)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:277)

最佳答案

确实,这不是我在阅读@TableGenerator 的 javadoc 后所期望的:

This annotation defines a primary key generator that may be referenced by name when a generator element is specified for the GeneratedValue annotation. A table 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).

也许我没有正确解释事情(JPA 规范的第 9.1.38 节没有告诉我们更多信息)但我期望能够从 @GeneratedValue 中的另一个实体引用生成器名称

无论如何,以下似乎有效。在 Dog 实体中:

@TableGenerator(table = "myseq", name = "dog_gen", pkColumnName = "seq_name", 
valueColumnName = "seq_val", pkColumnValue = "Dog", allocationSize = 1)
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "dog_gen")
private Long id;

Cat 中,也是一样的:

@TableGenerator(table = "myseq", name = "dog_gen", pkColumnName = "seq_name", 
valueColumnName = "seq_val", pkColumnValue = "Dog", allocationSize = 1)
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "dog_gen")
private Long id;

关于java - JPA @TableGenerator 在多个实体之间共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2741402/

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