@SequenceGenerator on class annotated with @MappedSuperclass

glaz666 picture glaz666 · Aug 31, 2010 · Viewed 18.2k times · Source

I have following structure of my entities:

@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 {}

And I got following exception:

    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

When I change @MappedSuperclass to @Entity on Intermed class, everything works OK. Are there any problems with using @MappedSuperclass and @SequenceGenerator? Or I have missed something?

Answer

Kallja picture Kallja · Jun 21, 2011

I ran into the same problem described in this question while trying to achieve application wide id generators.

The solution is actually in the first answer: put the sequence generator on the primary key field.

Like so:

@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 {}

While doing things this way seems remarkably stupid (at least to me) it does work.