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();
}



...全文
209 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

67,513

社区成员

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

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