hibernate.current_session_context_class为thread模式的使用问题
梦里乾坤 2014-05-12 06:18:58 最近在Java Web项目里配置了hibernate,在hibernate.cfg.xml中配置<property name="hibernate.current_session_context_class">thread</property>。在Java代码里用getCurrentSession()创建Session,在使用中可能是Session的打开关闭处理的不够好,有些Dao方法使用时就会报错,出现过的错误有:
1.org.hibernate.TransactionException: Transaction not successfully started
2.org.hibernate.HibernateException: createSQLQuery is not valid without active transaction
3.org.hibernate.SessionException: Session is closed!
4.org.hibernate.TransactionException: Transaction not successfully started
在网上搜索相关知识点,都是讲解thread模式下,Session如果遇到事务回滚或提交会自动关闭。下次获取Session时会新创建一个Session。那么我每个Dao方法都是以beginTransaction开始,commit结束。为什么有些方法就会出现这些异常而有些方法使用却是正常的呢??请大家帮忙指点一下!!!
以下贴出部分使用代码(主要是Session获取和close):
===============================HibernateUtil.java=========================================
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if (sessionFactory.isClosed()) {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
return sessionFactory;
}
}
==============================Initialize.java========================================
public class Initialize {
private Transaction trans = null;
private Session stmt = null;
//HibernateUtil HibernateUtil = new HibernateUtil();
public void start() {
try {
//stmt = HibernateUtil.getSessionFactory().openSession();
stmt = HibernateUtil.getSessionFactory().getCurrentSession();
trans = stmt.beginTransaction();
//trans.begin();
} catch (HibernateException hibernateException) {
hibernateException.printStackTrace();
}
public Transaction getTrans() {
return trans;
}
public void transCommit(){
try{
if(null!=getTrans()){
getTrans().commit();
}
}catch(Exception e){
e.printStackTrace();
}
}
public void close() {
try {
if (stmt != null) {
stmt.close();
}
// HibernateUtil.getSessionFactory().close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
================Dao方法里使用=======================
try {
sc.start();
Iterator it = sc.getStmt().createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list().iterator();
while (it.hasNext()) {
//这里数据遍历操作省略
}
} catch (Exception e) {
e.printStackTrace();
} finally {
sc.transCommit();
}