Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate @SequenceGenerator not global

I have two entity classes which use generated values

@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;

    ...
}

The problem is that if don't put the line

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

on both entities I get an error:

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.

What am I missing?

like image 386
Ayub Malik Avatar asked Nov 10 '22 13:11

Ayub Malik


1 Answers

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.

like image 128
neildo Avatar answered Dec 06 '22 17:12

neildo