Hibernate @SequenceGenerator不是全局的

时间:2014-02-08 13:53:16

标签: hibernate jpa annotations 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;

    ...
}

问题是如果不放线

@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen")
两个实体我收到错误:

Caused by: org.hibernate.AnnotationException: Unknown Id.generator: idgen

But the JPA spec says that the scope of the @SequenceGenerator is 'global' and can be reused across entities.

我错过了什么?

4 个答案:

答案 0 :(得分: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>

然后您不必在每个类中声明SequenceGenerator。

答案 1 :(得分:0)

规范的以下部分对我来说确实很奇怪。

  

生成器名称的范围对于持久性单元是全局的(跨所有生成器类型)。

我会像你一样解释它:可以在一个位置指定一个生成器,并在同一个持久性单元的任何地方重用它。就好像当前的Hibernate实现没有考虑这个句子。

是否有任何JPA / Hibernate规范专家可以帮助解释这句话?

答案 2 :(得分:0)

复制

@SequenceGenerator(allocationSize = 1, initialValue = 1000, name = "idgen")

进入Ent2应该可以,
您可以参考https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/seq-generator.html了解更多详情

答案 3 :(得分:0)

过去,Hibernate 对每个实体的序列进行范围限定,然后 JPA 说这应该是全局的,因此为了允许两者,引入了一个设置来控制它。您可以通过将 hibernate.jpa.compliance.global_id_generators 设置为 true 来启用全局范围。另请参阅有关详细信息的文档:https://docs.jboss.org/hibernate/orm/5.5/userguide/html_single/Hibernate_User_Guide.html#configurations-jpa-compliance