Hibernate @SequenceGenerator不是全局的

Ayu*_*lik 5 annotations hibernate jpa sequence-generators

我有两个使用生成值的实体类

@Entity
@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen")
public class Ent1 {
    @Id
    @GeneratedValue(generator = "idgen")
    private Long id;

    ...
}

@Entity
public class Ent2 {
    @Id
    @GeneratedValue(generator = "idgen")
    private Long id;

    ...
}
Run Code Online (Sandbox Code Playgroud)

问题是,如果不放线

@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen")
Run Code Online (Sandbox Code Playgroud)

两个实体上我收到一个错误:

Caused by: org.hibernate.AnnotationException: Unknown Id.generator: idgen
Run Code Online (Sandbox Code Playgroud)

但JPA规范说@SequenceGenerator的范围是"全局的",可以跨实体重用.

我错过了什么?

nei*_*ldo 1

这似乎是 Hibernate JPA 实现中的一个错误,因为它按照您期望的 EclipseLink JPA 实现方式工作(我测试了两者)。对于 Hibernate,只有当我使用 orm.xml 在应用程序级别声明 SequenceGenerator(假设您使用的是 JPA EntityManager)时,它才有效。如果您还没有 orm.xml,它将位于您的 persistence.xml 旁边。

下面是在 orm.xml 中声明序列生成器的示例:

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings
  xmlns="http://java.sun.com/xml/ns/persistence/orm"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
  version="2.0">

  <sequence-generator name="idgen" allocation-size="1" initial-value="1000" />

</entity-mappings>
Run Code Online (Sandbox Code Playgroud)

那么你就不必在每个类中声明SequenceGenerator。