[Solved] org.hibernate.AnnotationException

Recently I was working on a hibernate project and I have added few entity beans, when executed I got below exception stack trace.

The issue was coming because I forgot to specify primary key in my Entity bean, my bean was defined as;

Address.java

All I needed to fix the issue was to annotate the primary key field with @Id annotation. I changed my id field declaration to below and issue was resolved.

This is an easy fix but there is one scenario where it becomes more confusing. Usually hibernate automatically figures out the way to access the bean properties based on the annotations used on variable or getter-setter. However, We can explicitly define access type for our entity beans. There are two types of access types:

  1. Field: Hibernate will look for annotations on variables in this case, like we have defined for Address class above as @Access(value=AccessType.FIELD).
  2. Property: Hibernate will look for annotations on getter-setter methods in this case, syntax for this is @Access(value=AccessType.PROPERTY)

If the annotations are not defined as per access type, then also we will get this exception. For example if the access type is property and we have added all the annotations on bean variables, we will get this exception.

A sample class that will throw this exception is given below.

Employee.java

Notice that all the JPA annotations are used with getter methods whereas access type is defined as Field, just change the access type to property to solve this issue.

By admin

Leave a Reply

%d bloggers like this: