Home >Database >Mysql Tutorial >Hibernate 5: How to Fix the 'org.hibernate.MappingException: Unknown entity' Error?

Hibernate 5: How to Fix the 'org.hibernate.MappingException: Unknown entity' Error?

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 20:18:12777browse

Hibernate 5: How to Fix the

Hibernate 5: Resolving the "org.hibernate.MappingException: Unknown entity" Error

Introduction

While endeavoring to integrate Hibernate 5.0 with MySQL, developers often stumble upon the perplexing error message "org.hibernate.MappingException: Unknown entity." This issue stems from discrepancies in the configuration between Hibernate 4.3.9 and 5.0.0.

Root Cause

In Hibernate 5, the method configuration.buildSessionFactory(sr) causes the configuration to lose information about entity mappings configured via configuration.configure(). Consequently, Hibernate is unable to recognize the persistent classes.

Solution

To rectify this issue, modify the code responsible for creating the session factory:

// Incorrect approach (for Hibernate 5)
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(sr);

// Correct approach
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

Additional Options

1. Loading Properties

If the properties are stored in a non-default location, utilize the StandardServiceRegistryBuilder to load them:

ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
    .configure()
    .loadProperties("hibernate-<database>.properties")
    .build();
SessionFactory sessionFactory = new Configuration().buildSessionFactory(serviceRegistry);

2. Correcting the Hibernate 5 Tutorial

The Hibernate 5 tutorial contains an erroneous example in Section 1.1.6:

// Incorrect code from tutorial
return new Configuration().configure().buildSessionFactory(
                new StandardServiceRegistryBuilder().build() );

Replace this incorrect code with the correct approach:

// Correct code
return new Configuration().configure().buildSessionFactory();

The above is the detailed content of Hibernate 5: How to Fix the 'org.hibernate.MappingException: Unknown entity' Error?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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