5

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

@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

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

我错过了什么?

4

4 回答 4

1

This seems to be a bug in the Hibernate JPA implementation because it works how you expect with EclipseLink JPA Implementation (I tested both). With Hibernate, it only worked if I declared the SequenceGenerator at the application level using an orm.xml (assuming you are using JPA EntityManager). If you don't already have an orm.xml, it goes next to your persistence.xml.

Here's an example of declaring the sequence-generator in 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>

Then you don't have to declare the SequenceGenerator in each class.

于 2014-02-08T19:46:42.873 回答
0

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

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

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

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

于 2014-09-19T09:45:32.317 回答
0

复制

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

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

于 2020-02-20T01:57:31.893 回答
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

于 2021-06-24T07:17:53.167 回答