I have fixed the same issue with Hibernate 5. There is a problem in this code
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
SessionFactory sf = configuration.buildSessionFactory(sr);
This code works fine for Hibernate 4.3.5, but the same code has the same issue for Hibernate 5.
When you do configuration.buildSessionFactory(sr)
, using Hibernate 5, Configuration
losts all information about mapping that gets by call configuration.configure()
.
Solution
To fix the issue, if you use standard configuration files hibernate.cfg.xml
and hibernate.properties
, you can create the session factory by this way (without ServiceRegistry
)
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Loading properties
If you have properties in a file other then hibernate.properties
, you can build session factory using StandardServiceRegistryBuilder
(anyway, if you have hibernate.properties
and other file, it will be loaded both)
To load properties as a resource
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().
configure().loadProperties("hibernate-h2.properties").build();
SessionFactory sf = new Configuration().buildSessionFactory(serviceRegistry);
You need to have hibernate-h2.properties
in the class path (root of the sources folder, resources folder). You can specify a path from the root source folder too
/com/github/xxx/model/hibernate-h2.properties
.
To load properties from a 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);
You can find an example console application using this approach here fluent-hibernate-mysql. It uses a utility class to build the session factory from the fluent-hibernate library.
Incorrect Hibernate 5 tutorial
There is an incorrect example in Hibernate 5 tutorial 1.1.6. Startup and helpers. It uses this code
return new Configuration().configure().buildSessionFactory(
new StandardServiceRegistryBuilder().build() );
It doesn't do a proper configuration.