Hibernate does not pick up @Id annotation at getter

Viewed 887

Problem

In my current project I get this AnnotationException:

org.hibernate.AnnotationException: No identifier specified for entity: my.package.EntityClass

Defective Code

The problem is caused by the @Id annotation, which I moved from the field to the getter:

@Entity
@Table(name = "MY_TABLE")
public class EntityClass extends BaseEntityClass {

  private long id;

  @Override
  public void setId(long id) {
    this.id = id;
  }

  @Override
  @Id
  @SequenceGenerator(name = "FOOBAR_GENERATOR", sequenceName = "SEQ_MY_TABLE", allocationSize = 1, initialValue = 1)
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "FOOBAR_GENERATOR")
  public long getId() {
    return this.id;
  }

}

Working Code

When I annotate the id attribute instead, it works fine:

@Entity
@Table(name = "MY_TABLE")
public class EntityClass extends BaseEntityClass {

  @Id
  @SequenceGenerator(name = "FOOBAR_GENERATOR", sequenceName = "SEQ_MY_TABLE", allocationSize = 1, initialValue = 1)
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "FOOBAR_GENERATOR")
  private long id;

  @Override
  public void setId(long id) {
    this.id = id;
  }

  @Override
  public long getId() {
    return this.id;
  }

}

Reference to Documentation

The Hibernate documentation states:

By default the access type of a class hierarchy is defined by the position of the @Id or @EmbeddedId annotations. If these annotations are on a field, then only fields are considered for persistence and the state is accessed via the field. If there annotations are on a getter, then only the getters are considered for persistence and the state is accessed via the getter/setter. That works well in practice and is the recommended approach.

Question

My class has additional attributes, where I want to annotate the getters. So I need to put the @Id annotation at the getter as well.

This worked fine in other projects before, but this time Hibernate seems to not pick up the entity's identifier, when the getter is annotated.

  • Is there any additional configuration property I have to change?

  • Or did this behavious change between Hibernate versions?

1 Answers
Related