user1438038
user1438038

Reputation: 6059

Hibernate does not pick up @Id annotation at getter

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.

Upvotes: 4

Views: 1282

Answers (2)

peti
peti

Reputation: 846

Have you tried the @Access(AccessType.PROPERTY) annotation on your entity like this?

import javax.persistence.Access;
import javax.persistence.AccessType;

@Entity
@Access(AccessType.PROPERTY)
@Table(name = "MY_TABLE")
public class EntityClass extends BaseEntityClass {
...
}

Upvotes: 0

UserF40
UserF40

Reputation: 3601

You need to consistently use @Id on all the getters only then. Make sure no fields are annotated with @Id instead of getters. Mixing and matching will stop it working correctly.

Upvotes: 1

Related Questions