在使用Hibernate中,都需要如下操作:
1. 知道Hibernate配置
Configuration config = new Configuration().configure() ;
2. 从配置中取得SessionFactory
SessionFactory factory = config.buildSessionFactory() ;
3. 从SessionFactory中取得一个session
this.session = factory.openSession() ;
一般调用Hibernate都需要这些步骤,如果每次调用都需要执行这些代码,势必降低效率,所以通常情况下将Hibernate的初始化工作提取出来,单独的做成一个工具类:
代码如下:
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public final class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil () {
}
static {
Configuration cfg = new Configuration ();
cfg.configure (); // 此处缺省调用配置文件hibernate.cfg.xml,如果文件名不是这个,需要在这个地方进行配置
sessionFactory = cfg.buildSessionFactory ();
}
public static SessionFactory getSesstionFactory () {
return sessionFactory;
}
public static Session getSesstion () {
return sesstionFactory.openSesssion ();
}
}
如何调用呢?
public static void main (String [] args) {
Session s = HibernateUtil.getSession ();
// 事务处理
Transaction tx = s.beginTransaction ();
......
tx.commit ();
s.close ();
}
上面的代码还是不太规范,如下进行了一些优化:
......
Session s = null;
Transaction tx = null;
try {
s = HibernateUtil.getSession ();
tx = s.beginTransaction();
....
tx.commit ();
} catch (HibernateException e) { // catch 可以省略
if (tx != null) {
tx.rollback ();
}
throw e;
} finally {
if (s != null) {
s.close ();
}
}
......