【问题标题】:How to close connection using session factory如何使用会话工厂关闭连接
【发布时间】:2014-01-31 08:39:45
【问题描述】:

我是 spring mvc 和 hibernate 的新手。

如何在 spring mvc applction 中关闭连接。我对这个问题感到非常沮丧。

这是我的代码:

调度程序 servlet:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.kqics" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

    <bean id="userService" class="com.kqics.dao.kqtraveldao">
    </bean>

    <bean id="viewResolver1" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
        <property name="order" value="1"/>
        <property name="basename" value="views"/>
    </bean>

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <!-- one of the properties available; the maximum file size in bytes -->
        <property name="maxUploadSize" value="10000000" />
    </bean>

    <import resource="db-config.xml" />

</beans>

dbconfig.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p" 
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location"><value>/WEB-INF/jdbc.properties</value></property>
</bean>


<bean id="dataSourceBean" lazy-init="true" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">

        <property name="driverClass" value="${jdbc.driverClassName}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}"/>


        <property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
        <property name="minPoolSize" value="${jdbc.minPoolSize}" />
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
        <property name="maxIdleTime" value="${jdbc.maxIdleTime}" />
        <property name="numHelperThreads" value="${jdbc.numHelperThreads}" />


    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
                 p:dataSource-ref="dataSourceBean"
                 p:packagesToScan="com.kqics" >

        <property name="hibernateProperties">
        <props>
        <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <!--   <prop key="hibernate.hbm2ddl.auto">create</prop> --> 
        <prop key="hibernate.show_sql">true</prop>
        <prop key="hibernate.connection.release_mode">after_transaction</prop>
        <prop key="hibernate.connection.shutdown">true</prop>
        </props>
        </property>

    </bean>

    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
    <tx:annotation-driven/>

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ><ref bean="sessionFactory"/></property>

    </bean>


</beans>

我的服务类:

@Service
public class kqtravellogservice implements ikqtravellogservice {

@Autowired
ikqtraveldao iDao;

@Transactional
public void serviceaddnewvehicle(kqvehicle obj) {
    // TODO Auto-generated method stub

    iDao.addnewvehicle(obj);

}

@Transactional
public List<kqvehicle> servicefetchallvehicle() {

    return iDao.fetchallvehicle();
}

@Transactional
public void serviceaddnewvehicletariff(kqvehicletariff obj,String tariff) {

    iDao.addnewvehicletariff(obj,tariff);

}

道实现

public class kqtraveldao implements ikqtraveldao {

    private HibernateTemplate hibernateTemplate;

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        try {
            hibernateTemplate = new HibernateTemplate(sessionFactory);

        } catch (Exception w) {
        }

    }


    @Override
    public void addnewvehicle(kqvehicle obj) {


        hibernateTemplate.save(obj);

    }

    @SuppressWarnings("unchecked")
    @Override
    public List<kqvehicle> fetchallvehicle() {

        List<kqvehicle> li=null;

    li=hibernateTemplate.find("from kqvehicle");


    return li;
    }

    @Override
        public void addnewvehicletariff(kqvehicletariff obj, String tariff) {

            try
            {
            hibernateTemplate.getSessionFactory()
            .openSession()
            .createSQLQuery("insert into "+tariff+" values(?,?,?,?,?)")
            .setParameter(0, obj.getTid())
            .setParameter(1, obj.getVehicletype())
            .setParameter(2, obj.getRupees())
            .setParameter(3, obj.getDateupto())
            .setParameter(4, obj.getDatetimedetermined())
            .executeUpdate();
            }
            catch(Exception e)
            {

            }
            finally
            {
                hibernateTemplate.getSessionFactory().close();

            }


        }

一些朋友告诉我,因为我没有使用单例,连接关闭..所以,我得到了太多的连接错误......请告诉我如何解决这个问题......

我的代码需要进行哪些更改......

【问题讨论】:

    标签: java spring hibernate spring-mvc hibernate-annotations


    【解决方案1】:

    问题出在您的 dao 中,您的保存方法正在破坏 springs 正确的 tx 管理。当您使用 Spring 管理连接和会话时,您永远不应该调用 openSession()

    改为使用HibernateCallback,这将为您提供春季托管会话。

    @Override
    public void addnewvehicletariff(final kqvehicletariff obj, final String tariff) {
        hibernateTemplate.execute(new HibernateCallback() {
            public Object doInHibernate(Session session) {
                session.createSQLQuery("insert into "+tariff+" values(?,?,?,?,?)")
                .setParameter(0, obj.getTid())
                .setParameter(1, obj.getVehicletype())
                .setParameter(2, obj.getRupees())
                .setParameter(3, obj.getDateupto())
                .setParameter(4, obj.getDatetimedetermined())
                .executeUpdate();   
            }
        }
    }
    

    另一个注意事项是您不应该再使用HibernateTemplate,您应该使用SessionFactory 上的getCurrentSession() 方法针对普通休眠API 编写代码。请参阅http://docs.spring.io/spring/docs/current/spring-framework-reference/html/orm.html#orm-hibernate-straight 了解更多信息。

    public class kqtraveldao implements ikqtraveldao {
    
        private SessionFactory sessionFactory;
    
        @Autowired
        public void setSessionFactory(SessionFactory sessionFactory) {
            this.sessionFactory=sessionFactory;
        }
    
        @Override
        public void addnewvehicle(kqvehicle obj) {
            sessionFactory.getCurrentSession().save(obj);
        }
    
        @SuppressWarnings("unchecked")
        @Override
        public List<kqvehicle> fetchallvehicle() {
            return sessionFactory.getCurrentSession()
                .createQuery("from kqvehicle")
                .list(); 
        }
    
        @Override
        public void addnewvehicletariff(kqvehicletariff obj, String tariff) {
            sessionFactory.getCurrentSession()
            .createSQLQuery("insert into "+tariff+" values(?,?,?,?,?)")
            .setParameter(0, obj.getTid())
            .setParameter(1, obj.getVehicletype())
            .setParameter(2, obj.getRupees())
            .setParameter(3, obj.getDateupto())
            .setParameter(4, obj.getDatetimedetermined())
            .executeUpdate();
        }
    }
    

    【讨论】:

    • 感谢 Deinum,您能否解释一下什么是单例对象以及我们在上面的代码中使用 单例对象 的位置。
    • 您的代码已经使用了单例,所以不确定您要解释什么。
    • 嗨,Deinum,我已经按照你上面提到的那样更改了我的应用程序,但现在我仍然遇到了类似的问题。我已经发布了另一个关于堆栈溢出的查询,请访问。这个链接..stackoverflow.com/questions/21520106/…
    • 如果你有多个 daos,你应该把它们都改掉。
    • 我只有一个 dao 类,我已经按照您的建议更改了我的应用程序中的所有内容。但我仍然收到这些错误 org.springframework.transaction.CannotCreateTransactionException: 无法为事务打开 Hibernate 会话; org.hibernate.TransactionException: JDBC 开始失败: java .net.SocketTimeoutException:读取超时 com.mchange.v2.resourcepool.TimeoutException:客户端在等待从com.mchange.v2.resourcepool.BasicResourcePool@1c5950a9获取资源时超时--超时在 awaitAvailable()
    【解决方案2】:

    只需在 dao 中自动装配 sessionfactory 并删除方法集 session factory。

    @Autowired
    private SessionFactory sessionfactory;
    

    你可以通过在你的方法中调用sessionfactory.getCurrentSession().close()来关闭连接。

    会话工厂是您应用程序中的“单例”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-06
      • 2015-08-23
      • 2016-01-19
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多