Intellj IDEA 使用Hibernate5.2.3 新建映射文件:
点击 VIew -- Tool Window --- Persistence 选择文件,右键选中 Generate Persistence Mapping -- by Database Schema。
出现下面界面
1、配置号数据源,填写映射文件保存路径
2、点击“刷新”按钮,会出现数据库中所有表结构,选择需要映射的表。勾选 Generate Separate XML per Entity。
3、点击ok
此时在映射文件包名下出现了对于的类文件和映射文件(***.hbm.xml文件)。
编写测试类测试:
注意SessonFactory的获取代码如下。
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
configuration.addResource("com/junxu/UserEntity.hbm.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
ServiceRegistry ssr = ssrb.build();
sessionFactory = configuration.buildSessionFactory(ssr);
注意,**.hbm.xml文件不是在hibernate.cfg.xml中配置。而是在代码中加载。
同时:如果在使用Hibernate5.2.3中出现如下错误:
org.hibernate.UnknownEntityTypeException: Unable to locate persister: com.junxu.UserEntity
查看 **.hbm.xml文件是不是在hibernate.cfg.xml中配置了。若是,将其在配置文件删除,改用上述方式即可。