Home >Java >javaTutorial >How to Fix \'org.hibernate.MappingException: Unknown entity\' Error in Hibernate 5 with MySQL?
Hibernate 5: Resolving the "org.hibernate.MappingException: Unknown entity" Error
When integrating Hibernate 5.0 with MySQL, you may encounter the error "org.hibernate.MappingException: Unknown entity." This issue arises specifically with Hibernate versions 5.0.0 and 5.0.1, while Hibernate 4.3.9 operates without this problem.
Cause of the Error
In Hibernate 5, a change in the way Hibernate reads its configuration led to this error. Specifically, the configuration information read from hibernate.cfg.xml is not properly applied when using the StandardServiceRegistryBuilder to construct the SessionFactory.
Solution
To resolve this error, there are a few approaches to consider:
Using the Basic Configuration Method
For a simpler solution, avoid using the StandardServiceRegistryBuilder and instead create the session factory directly from the Configuration object:
<code class="java">SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();</code>
Loading Properties
If you have additional properties defined outside of hibernate.properties, you can load them using the StandardServiceRegistryBuilder:
<code class="java">ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .configure() .loadProperties("hibernate-h2.properties") .build(); SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);</code>
Using Fluent-Hibernate
You can also utilize the fluent-hibernate library for a more convenient approach, as demonstrated in the GitHub project "fluent-hibernate-mysql."
Additional Considerations
Note that the Hibernate 5 tutorial's example in Section 1.1.6 is incorrect. It fails to load the proper configuration when building the SessionFactory, leading to mapping issues.
The above is the detailed content of How to Fix \'org.hibernate.MappingException: Unknown entity\' Error in Hibernate 5 with MySQL?. For more information, please follow other related articles on the PHP Chinese website!