org.hibernate.SessionException: Session is closed! 流程:
读取action然后把List的数据显示到页面上
Java code
public List findAllCardinfo(String userid, Long cardid) {
Session session = HibernateSessionFactory.getSession();
StringBuffer sb = new StringBuffer();
Transaction tx = null;
Query queryObject = null;
try {
tx = session.beginTransaction();
sb
.append("select new com.telezone.vo.CardinfoVO( cinfo.cardid ,cinfo.cardname , oinfo.ownername ,uinfo.username , cinfo.phonenum,cinfo.cardstate,cinfo.createtime,cinfo.otherinfo ) from Cardinfo as cinfo left join cinfo.cardownerinfo as oinfo left join cinfo.userinfo as uinfo where uinfo.userid = :uid ");
// Long 类型 cardid 默认取值 0
if (cardid > 0)
sb.append(" and cinfo.cardid = :cid");
sb.append(" order by cinfo.cardid");
queryObject = session.createQuery(sb.toString());
queryObject.setParameter("uid", userid);
if (cardid > 0)
queryObject.setParameter("cid", cardid);
tx.commit();
} catch (RuntimeException re) {
tx.rollback();
log.error("==CardinfoServices findAllCardinfo failed==", re);
re.printStackTrace();
} finally {
session.close();
}
return queryObject.list();
}
把session.close()注释掉就可以了
但是session不是用完就需要关闭的吗?
用的是Struts+Hibernate
------解决方案-------------------- finally在return前执行的,所以你是在关闭了session之后才返回,你觉得 这样会有数据么?
要么把return放在TRY里面,要么在前面定义一个list,然后在try里面list=queryObject.list();才能返回.
------解决方案-------------------- 正解:Hibernate使用了延迟加载Lazy,当你真正使用session的时候才会去执行查询。“queryObject.list();”这句才开始执行后台数据库查询 而你已经在finally中将session关闭
你可以去看下hibernate的延迟加载
------解决方案-------------------- 探讨 Hibernate使用了延迟加载Lazy,当你真正使用session的时候才会去执行查询。“queryObject.list();”这句才开始执行后台数据库查询 而你已经在finally中将session关闭
------解决方案-------------------- 写在web.xml中 让session一直开着
<filter>
<filter-name>openSession</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>openSession</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
------解决方案-------------------- 将关联类的class级别lazy也设成false
------解决方案-------------------- 同意4楼,
public List findAllCardinfo(String userid, Long cardid) {
Session session = HibernateSessionFactory.getSession();
StringBuffer sb = new StringBuffer();
Transaction tx = null;
Query queryObject = null;
List rlist=null;
try {
tx = session.beginTransaction();
sb
.append("select new com.telezone.vo.CardinfoVO( cinfo.cardid ,cinfo.cardname , oinfo.ownername ,uinfo.username , cinfo.phonenum,cinfo.cardstate,cinfo.createtime,cinfo.otherinfo ) from Cardinfo as cinfo left join cinfo.cardownerinfo as oinfo left join cinfo.userinfo as uinfo where uinfo.userid = :uid ");
// Long 类型 cardid 默认取值 0
if (cardid > 0)
sb.append(" and cinfo.cardid = :cid");