Hibernate 项目查询数据报 UnknownEntityTypeException

时间:2021-07-14 20:08:06

Hibernate 项目查询数据报 UnknownEntityTypeException

原因分析:

1. hibernate.cfg.xml配置文件有没有映射实体类

 <mapping resource="/***/***/***.hbm.xml"/>

 2、hibernate 5 创建 Session时,需加上cfg.addClass(**.class);

package com.example;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
 * @Classname HibernateTest
 * @Description TODO
 * @Date 2019-8-6 15:57
 * @Created by Administrator
 */
public class HibernateTest {
    public static void main(String[] args) {
        // 1、读取hibernate。cfg.xml配置文件
        Configuration cfg = new Configuration().configure();
        cfg.addClass(Books.class);
        // 2、创建服务注册
        ServiceRegistry registry = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties())
                .build();
        // 3、新建SessionFactory对象
        SessionFactory factory = cfg.buildSessionFactory(registry);
        // 4、创建session对象
        Session session = factory.openSession();
        // 5、获取数据
        Books books = (Books) session.get(Books.class,"8");
        System.out.println(books);
        // 6、释放资源
        session.close();
        factory.close();

    }
}

修改完成后可正常运行:

Hibernate 项目查询数据报 UnknownEntityTypeException