Frequent Hibernate Issue: No Identifier Specified for Entity

When using Hibernate, you may encounter the error message “AnnotationException: No identifier specified for entity.” In our latest blog post, we present a simple solution to this common problem.

While running some projects containing entity beans, I encountered the following error message:

Initial SessionFactory creation failed.org.hibernate.AnnotationException: No identifier specified for entity: com.journaldev.hibernate.model.Address
...
Exception in thread "main" java.lang.ExceptionInInitializerError

Cause of this Hibernate Issue

This error occurs when a primary key is not specified in the entity bean. An example of this is the Address.java bean, which was defined as follows, but without the necessary @Id annotation for the primary key field:

@Entity
@Table(name = "ADDRESS")
@Access(value=AccessType.FIELD)
public class Address {
    // ... fields without @Id annotation ...
}

Solution to this Hibernate Issue

The solution is to add the @Id annotation to the primary key field:

@Id
@Column(name = "emp_id", unique = true, nullable = false)
@GeneratedValue(generator = "gen")
@GenericGenerator(name = "gen", strategy = "foreign", parameters = {@Parameter(name = "property", value = "employee")})
private long id;

A Common Misunderstanding: Access Types in Hibernate

Another confusing scenario arises when it comes to access types in Hibernate. Hibernate can access bean properties in two ways:

  1. Field access (AccessType.FIELD): Hibernate looks for annotations on variables.
  2. Property access (AccessType.PROPERTY): Hibernate looks for annotations on getter and setter methods.

If the annotations are not set according to the defined access type, this also leads to an AnnotationException. In the Employee.java bean, this error occurred because all JPA annotations were applied to getter methods, even though the access type was defined as field. The correction involved changing the access type to AccessType.PROPERTY.

Conclusion

This experience underscores the importance of knowing and adhering to the details and specifications of Hibernate. A small oversight or misunderstanding can lead to hours of debugging. Hopefully, this post will help other developers quickly resolve similar issues.

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: