hibernate Util类的写法

javajb 2011-05-16 03:55:35
看看下面的util有问题么?

public class HibernateUtil {

private static Configuration config;
private static SessionFactory sessionFactory;
private static Session session;
private static Transaction tx;
private static final ThreadLocal local = new ThreadLocal();

/**
* 初始化配置文件,放在静态代码块中,表示只执行一次
*/
static {
config = new Configuration().configure();
sessionFactory = config.buildSessionFactory();
}

/**
* 获取Session
*
*/
public static Session getSession() {
session = (Session) local.get();
if (session == null) {
session = sessionFactory.openSession();
}
tx = session.beginTransaction();
return session;
}

/**
* 关闭Session
*/
public static void close() {
if (session != null) {
tx.commit();
session.close();
}
}

}
...全文
67 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
猿敲月下码 2011-05-16
  • 打赏
  • 举报
回复
LZ看下这个
package util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

public static final SessionFactory sessionFactory;

static {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration config = new Configuration().configure();
sessionFactory = config.buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static final ThreadLocal session = new ThreadLocal();

public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();
// Open a new Session, if this thread has none yet
if (s == null) {
s = sessionFactory.openSession();
// Store it in the ThreadLocal variable
session.set(s);
}
return s;
}

public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
}

67,514

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧