使用@MappedSuperclass注释的类上的@SequenceGenerator
我有以下我的实体结构:
@MappedSuperclass public abstract class BaseEntity { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqGenerator") private Long id; } @MappedSuperclass @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @SequenceGenerator(name = "seqGenerator", sequenceName = "DICTIONARY_SEQ") public abstract class Intermed extends BaseEntity {} @Entity public class MyEntity1 extends Intermed {} @Entity public class MyEntity2 extends Intermed {}
我得到以下例外:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [context/applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Unknown Id.generator: seqGenerator
当我在Intermed类上将@MappedSuperclass更改为@Entity时,一切正常。 使用@MappedSuperclass和@SequenceGenerator有什么问题吗? 或者我错过了什么?
以下是JPA 1.0规范关于SequenceGenerator
注释的内容:
9.1.37 SequenceGenerator注释
SequenceGenerator
注释定义了主键生成器,当为GeneratedValue
批注指定GeneratedValue
器元素时,可以通过名称引用该GeneratedValue
。 可以在实体类或主键字段或属性上指定序列生成器。 生成器名称的范围对于持久性单元是全局的(跨所有生成器类型)。
映射的超类不是实体。 所以根据我阅读规范的方式,你想做什么是不可能的。 要么将Intermed
类设为实体,要么将SequenceGenerator
放在子类上。
在尝试实现应用程序范围的id生成器时,我遇到了此问题中描述的相同问题。
解决方案实际上是第一个答案: 将序列生成器放在主键字段上 。
像这样:
@MappedSuperclass public abstract class BaseEntity { @Id @SequenceGenerator(name = "seqGenerator", sequenceName = "DICTIONARY_SEQ") @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seqGenerator") private Long id; } @MappedSuperclass @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public abstract class Intermed extends BaseEntity {} @Entity public class MyEntity1 extends Intermed {} @Entity public class MyEntity2 extends Intermed {}
虽然以这种方式做事似乎非常愚蠢(至少对我来说)确实有效。
- NoClassDefFoundError:org / hibernate / annotations / common / reflection / MetadataProvider
- Hibernate,id,oracle,sequence
- javax.persistence.PersistenceException:未找到类或包
- JPA:如何在运行时指定与类对应的表名?
- 使用SequenceGenerator的javax.persistence.EntityExistsException
- 使用列上的别名查询会出错
- 原生查询(JPA)未重置并返回相同的旧结果
- 模式validation:缺少表
- 什么是@JoinColumn以及如何在Hibernate中使用它