使用hibernate最新版本:hibernate-release-4.2.5.Final
本文是对之前的hibernate4 annotation实例的补充说明
hibernate4配置文件头信息(不可缺省)为:
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
MySQL方言是:MySQL5Dialect不在是MySQLDialect(写MySQLDialect也不报错,也可以通过)
注意:获取SessionFactory新的方式(new Configuration().configure().buildSessionFactory()方法已过时)
Configuration configuration = new Configuration();
configuration.configure();//默认在classpath下找hibernate.cfg.xml配置文件
//可指定路径
//configuration.configure("/db/hb.cfg.xml");//classpath下找db文件夹下的hb.cfg.xml
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
xml,annotation都可以通过上面方式
annotation获取SessionFactory可通过指定注解的类获取,这样的好处就是不需要在hibernate.cfg.xml配置 <mapping>标签了
sessionFactory = configuration.addAnnotatedClass(Teacher.class).buildSessionFactory.(serviceRegistry);
获取Session:
Session session = sessionFactory.getCurrentSession();//推荐使用
getCurrentSession()与openSession()的区别
1、getCurrentSession () 使用当前的session openSession() 重新建立一个新的session
* 采用getCurrentSession()创建的session会绑定到当前线程中,而采用openSession()
创建的session则不会
* 采用getCurrentSession()创建的session在commit或rollback时会自动关闭,而采用openSession()
创建的session必须手动关闭
2、使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置:
* 如果使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事务(jta事务)java分布式事务管理(多数据库访问)
jta由中间件提供(jboss WebLogic等,tomcat不支持)
<property name="hibernate.current_session_context_class">jta</property>
getCurrentSession()使用方法
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(t);
session.getTransaction().commit();
openSession()使用方法
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(t);
tx.commit();
session.close();
junit测试遇到的问题:创建SessionFactory初始化异常不提示,比如指定配置文件时写错文件名或者路径,junit不报错。
解决办法:使用try/catch
try {
configuration.configure("/db/hb.cfg.xml");
} catch (HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
另一方法是使用main方法测试,个人感觉不好,不够专业,junit是专门的单元测试