Home > Java > javaTutorial > How to Fix \'org.hibernate.MappingException: Unknown entity\' Error in Hibernate 5 with MySQL?

How to Fix \'org.hibernate.MappingException: Unknown entity\' Error in Hibernate 5 with MySQL?

DDD
Release: 2024-11-02 15:47:29
Original
597 people have browsed it

How to Fix

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template