Wednesday, August 2, 2017

org.hibernate.MappingException: Unknown entity

Developers working in Hibernate must have come across the above error some point of their life, particularly those working initially. I am not saying everybody faces the above issue, but sometimes most of the beginner come across the issue.
If you check the stack trace,  you will see the message “org.hibernate.MappingException: Unknown entity:” followed by a model name. In the stack trace you can see list of exception somewhat like the one mentioned below.
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:679)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:837)
at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:833)

I have just mentioned few lines of the exception shown in the stack trace as putting whole stack trace will take a lot of space which is not required. The error is bit confusing and takes a few minutes to few hours depending upon the experience of the developer. The reason for the exception is how ever quite simple and taking a little care will resolve the issue.
I found two issues for the above exception which I mentioned below
1.       As you know both hibernate and JPA has @Entity annotation. Eclipse was automatically importing org.hibernate.annotations.Entity instead of javax.persistence.Entity annotation, or you might by mistake used the hibernate.annotation.Entity instead of Javax.persistent.entity in your model class. So make the changes to your model class, recompile the code and try to run the code now. It will solve the issue in case you have made the above mistake else follow the next instruction.

2.       If you have imported javax.persistent,entity in your class and still facing the above issue then it is time to visit your application’s  servlet.xml file.  Check you bean for sessionFactory. Check property named annotatedClasses and see in the value section if you have mentioned the model name correctly. If you don’t have the model name here then add it or if you have misspelled it, the correct the name of the model. Save the changes and compile and run the application.

In my case I have used and hibernate 4.1 and spring 3.6 and came across the above exception when by mistake I have missed to add the model class in the annotatedClasses property file of my servlet.xml

No comments:

Post a Comment