1

I am new to spring mvc and hibernate.

How to close connection in spring mvc applction. I am very frustrated from this issue.

This is my code:

Dispatcher 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>

my service class:

@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);

}

dao impl

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

            }


        }

Some friends told me as i am not using singleton, connection closing.. so, i got the too many connection error... Please advice me how to resolve this problem...

What are the changes is needed for my code....

M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Vijay Leo
  • 109
  • 2
  • 4
  • 11

2 Answers2

0

The problem is in your dao, your save method is destroying springs proper tx management. You should NEVER call openSession() when you are using Spring to manage your connections and sessions.

Instead use a HibernateCallback which will give you a spring managed session.

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

Another note is that you shouldn't be using HibernateTemplate anymore, you should write code against the plain hibernate API using the getCurrentSession() method on the SessionFactory. See http://docs.spring.io/spring/docs/current/spring-framework-reference/html/orm.html#orm-hibernate-straight for more information.

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();
    }
}
M. Deinum
  • 115,695
  • 22
  • 220
  • 224
  • Thanks Deinum, Could you please explain what is singleton object and where we used **singleton object** in above code. – Vijay Leo Jan 31 '14 at 09:39
  • Your code already used a singleton so not sure what you want to have explained. – M. Deinum Jan 31 '14 at 09:40
  • Hi Deinum, I have changed my application as you mentioned above, but still now i got the similar problems. I have post the another query to stack overflow please visit. this link.. http://stackoverflow.com/questions/21520106/tomcat-server-not-loading-more-than-2-applications/21520369?noredirect=1#21520369 – Vijay Leo Feb 03 '14 at 06:36
  • If you have multiple daos you should have changed all of them. – M. Deinum Feb 03 '14 at 07:13
  • I have only one dao class and i have changed everything in my app as you suggested way. but still i got these errors **org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction;** **org.hibernate.TransactionException: JDBC begin failed:** **java.net.SocketTimeoutException: Read timed out** **com.mchange.v2.resourcepool.TimeoutException: A client timed out while waiting to acquire a resource from com.mchange.v2.resourcepool.BasicResourcePool@1c5950a9 -- timeout at awaitAvailable()** – Vijay Leo Feb 03 '14 at 07:28
0

just autowire the sessionfactory in the dao and remove the method set session factory.

@Autowired
private SessionFactory sessionfactory;

you can close the connection by calling sessionfactory.getCurrentSession().close() in your method.

the Session factory is the 'singleton' in your application.

Orchid
  • 223
  • 3
  • 11