Hibernate 5;org.hibernate.MappingException: Unknown entity: com.my.model.User

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.
url:https://stackoverflow.com/questions/32405031/hibernate-5-org-hibernate-mappingexception-unknown-entity

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值