看看下面的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();
}
}}
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();
}
}}
解决方案 »
- @Resource按类名注射报错,大大们求教啊~~~~
- 【求助帖】求一个Struts+Hibernate+Spring项目
- 为什么不输出内容而是输出地址?
- 请问:hibernate里的session如何正确关闭
- 新手提问题,在线等。用myeclipse运行struts2例子出现404错误详细信息如下
- Spring中value和ref的区别?
- Java已经大改变?
- J2EE框架中多个WEB模块的授权问题
- 有看过j2ee tutorial 1.3中文版的高手么帮个忙,我按书里说明打包j2ee应用程序客户端,生成的jar文件老是加不进ConverterApp.ear文件中?
- 带有static的方法可以用对象.调用吗?
- 奇怪问题!!!!!!!
- 这段代码写在方法里面的,用于把服务端exportFile.txt下载到本地。但是下载之后的txt会比原来的文件要小,请大家帮忙解决一下!
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);
}
}