Hibernate 5: Resolving "org.hibernate.MappingException: Unknown entity" Issue
The "org.hibernate.MappingException: Unknown entity" error commonly encountered when integrating Hibernate 5 with database systems stems from a configuration issue. This occurs specifically for Hibernate versions 5.0.0 and 5.0.1.
Configuration Flaw
The problem lies within the sessionFactory creation process. The following code snippet from the sample code provided illustrates the issue:
SessionFactory sf = configuration.buildSessionFactory(sr);
When attempting to build the session factory using the buildSessionFactory method while passing in the ServiceRegistry, Hibernate 5 loses track of the mapping information previously loaded via the configure method.
Solution
To rectify this issue, alternative approaches for creating the session factory can be employed, depending on the configuration being used.
Loading Properties
For standard configuration files (hibernate.cfg.xml and hibernate.properties), the session factory can be created without utilizing the ServiceRegistry as seen below:
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Alternatively, if properties are stored in a file other than hibernate.properties, they can be loaded using the StandardServiceRegistryBuilder:
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .configure() .loadProperties("hibernate-h2.properties") .build(); SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);
Similarly, properties can also be loaded from a specific path in the file system:
File propertiesPath = new File("some_path"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .configure() .loadProperties(propertiesPath) .build(); SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);
The above is the detailed content of Hibernate 5: How to Solve 'org.hibernate.MappingException: Unknown entity'?. For more information, please follow other related articles on the PHP Chinese website!