hibernate 執行幾條數據後報連接數據庫失敗

終於找到解決辦法了 ,咱們來看下面的內容吧
php

ItemDAOImpl.java
html

public class ItemDAOImpl extends HibernateDaoSupport implements ItemDAO {
java


public List queryAll() throws Exception {
spring

// TODO Auto-generated method stub
數據庫

Session session=super.getSession(true);
session

String hql="from Item as i";
app

List l=super.getSession().createQuery(hql).list();
測試

return l;
ui

}
url

}\

其實上面的代碼隱藏了一個問題,數據庫鏈接並無被關閉,因此一直出現以上的問題。

我這裏提供三個解決方案

方案一:

用此種方法,雖然沒有手動關閉數據庫鏈接,但spring已經幫咱們關閉了

return super.getHibernateTemplate().find(hql);

方案二:(經測試,此方案比較有效)

設定HibernateTemplateAllowCreateTrue

spring API HibernateDaoSupport

protected net.sf.hibernate.Session getSession(boolean allowCreate)

Get a Hibernate Session, either from the current transaction or a new one.

public class ItemDAOImpl extends HibernateDaoSupport implements ItemDAO {


public List queryAll() throws Exception {

// TODO Auto-generated method stub

Session session=super.getSession(true);

String hql="from Item as i";

List l=session.createQuery(hql).list();

try{

return l;

}finally{

session.close();

}

}

}

方案三:

Spring API:
geSession()org.springframework.orm.hibernate3.support.HibernateDaoSupport 中的一個方法,

它能夠從當前事務或者一個新的事務得到一個hibernate sessionsession.

修改後的代碼以下:


public class ItemDAOImpl extends HibernateDaoSupport implements ItemDAO {

public List queryAll() throws Exception {

// TODO Auto-generated method stub

Session session = super.getSession();

String hql = "from Item as i";

List l = session.createQuery(hql).list();

releaseSession(session);


}

}

困擾了幾天的問題終於解決了,項目擱淺了好幾天了,就是對springsession的管理不清楚。

相關文章
相關標籤/搜索