Hibernate doesn't pick up @Id annotation on getter

Problem

In my current project, I am getting this AnnotationException

:

org.hibernate.AnnotationException: no identifier specified for object: my.package.EntityClass

Defective code

The problem is caused by the annotation @Id

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 comment out instead of the attribute id

, it works great:

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

}

      

Link to documentation

Hibernate documentation says:

By default, the access type of a class hierarchy is determined by the position of the @Id or @EmbeddedId annotations. If these annotations are in the field, then only the fields are saved for saving and the state is accessed through the field. If annotations are present on the getter, then only the getters are saved for persistence, and the state is accessed through the getter / setter. This works well in practice and is the recommended method.

Question

My class has additional attributes where I want to annotate getters . So I need to put annotation @Id

on the getter.

This has worked well in other projects before, but this time Hibernate doesn't seem to pick up the object id when the getter is annotated.

  • Is there any additional config property that I should change?

  • Or could this have changed between Hibernate versions?

+3


source to share


1 answer


You only need to use consistently @Id

for all getters then. Make sure no fields are annotated with @Id

getters instead. Mixing and matching will stop it working.



0


source







All Articles