Hibernate 5 初次使用遇到的各种问题

问题一:
MyEclipse2016 第一次配置,项目右键new里没有Hibernate XML Mapping File,与教程上不同

解决方法:
新建XML(Basic Templates),创建过程中命名为TableName.hbm.xml,选取Create XML file from a DTD file,在select XML Catalog entry 中 选取Hibernate Mapping DTD 3.0,即可创建

问题二:
运行报错,Unable to create requested service

解决方法:
检查jdbc相关的配置是否正确,我原因是hibernate.cfg.xml里jdbc驱动包名写错

问题三:
运行报错,org.hibernate.MappingException: Unknown entity

解决方法:
教程中是hibernate 4 ,而我用的实际是hibernate 5
两者在ServiceRegistry等方法上不一样

4.x版本

private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;

//init
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = config.buildSessionFactory(serviceRegistry);
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();

//Destory
transaction.commit();
session.close();
sessionFactory.close();

5.x版本

private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;

//init
Configuration config = new Configuration().configure();
sessionFactory = config.configure().buildSessionFactory();  
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();

//destory
transaction.commit();

问题四:
错误:org.hibernate.HibernateException: No CurrentSessionContext configured!

解决方法:
在hibernate.cfg.xml中添加

<property name="current_session_context_class">threadproperty>  

问题五:
错误org.hibernate.exception.GenericJDBCException: could not execute statement

解决方法;
数据库表中,主键设置自动递增

你可能感兴趣的:(hibernate)