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.ExceptionInInitializerErrorCause 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 ...
}Matching infrastructure at centron
Databases need care in production: centron can take over updates, backups and monitoring – from a single instance to a full cluster. Explore managed clusters →
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:
- Field access (
AccessType.FIELD): Hibernate looks for annotations on variables. - 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.
Testen Sie Ihr Setup auf ccloud³
Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.