Bug #10917 session.close() using Hibernate don´t close really
Submitted: 27 May 2005 14:39 Modified: 17 Jul 2009 23:18
Reporter: Esley Bonomo Email Updates:
Status: Not a Bug Impact on me:
None 
Category:Connector / J Severity:S2 (Serious)
Version:3.0.15 OS:Windows (Windows XP)
Assigned to: CPU Architecture:Any

[27 May 2005 14:39] Esley Bonomo
Description:
Hi,

I'm having problem with query using Hibernate. After some querys, this error appears:
java.sql.SQLException: Data source rejected establishment of connection,  message from server: "Too many connections"
	at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:649)
	at com.mysql.jdbc.Connection.createNewIO(Connection.java:1782)
	at com.mysql.jdbc.Connection.<init>(Connection.java:450)
        .....

And I close all sessions in all methods. But I think that this method (session.close()) not is closing this session correctly.

How to repeat:
This are my class:

/*============ConnectionDAO.java==================
 */
package com.planet.gametimer.db.dao;

import java.sql.SQLException;

import com.planet.exception.DAOException;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.MappingException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;

/**
 * @author Bonomo
 */
public class ConnectionDAO {

	protected Session session;
	protected SessionFactory factory;
    
	public ConnectionDAO(Class c) throws DAOException, MappingException{
    	try {
	    	Configuration cfg = new Configuration()
		    .addClass(c);
	        factory = cfg.buildSessionFactory();
    	} catch (HibernateException hex){
    		throw new DAOException(hex.toString());
    	}
    }
	
    public Session getSession() throws DAOException {
    	try {
    		if (session == null)
    			session = factory.openSession();
	        return session;
	    } catch (HibernateException hex){
    		throw new DAOException(hex.toString());
    	}
    }
    
    public void close() throws DAOException{
    	try {
	    	session.flush();
	    	session.connection().commit();
	    	session.close();
	    } catch (SQLException e) {
	    	throw new DAOException(e.toString());
		} catch (HibernateException hex){
    		throw new DAOException(hex.toString());
    	}
    }
}

/*
 ===============MaquinaDAO.java======================
 */
package com.planet.gametimer.db.dao;

import java.util.List;

import com.planet.exception.DAOException;
import com.planet.gametimer.db.Maquina;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.MappingException;

/**
 * @author Bonomo
 */

public class MaquinaDAO extends ConnectionDAO{

    public MaquinaDAO() throws DAOException, MappingException{
    	super(Maquina.class);
    }
    
    public java.util.List findAll() throws DAOException{
    	try {
	        List maquinas = getSession().find("from Maquina order by Nome");
	        return maquinas;
	    } catch (HibernateException hex){
			throw new DAOException(hex.toString());
		} finally {
            close();
        }
    }
    
}

/*
 ===============DAOException.java======================
 */
package com.planet.exception;

/**
 * @author Bonomo
 */
public class DAOException extends Exception {

	public DAOException() {
		super();
	}

	public DAOException(String message) {
		super(message);
	}

	public DAOException(Throwable cause) {
		super(cause);
	}

	public DAOException(String message, Throwable cause) {
		super(message, cause);
	}

}

/*
 ==================Maquina.java=====================
 */
package com.planet.gametimer.db;

/**
 * @author Bonomo
 */

public class Maquina {

	private Integer id;
	private String nome;
	private Float preco1;
	private Float preco2;
	private String bonus;
	
	public Integer getId() {
		return id;
	}
	
	public void setId(Integer value) {
		id = value;
	}
	
	public String getNome() {
		return nome;
	}
	
	public void setNome(String value) {
		nome = value;
	}
	
	public Float getPreco1() {
		return preco1;
	}
	
	public void setPreco1(Float value) {
		preco1 = value;
	}
	
	public Float getPreco2() {
		return preco2;
	}
	
	public void setPreco2(Float value) {
		preco2 = value;
	}
	
	public String getBonus() {
		return bonus;
	}
	
	public void setBonus(String value) {
		bonus = value;
	}
	
}

/*
=============Maquina.hbm.xml==========================
*/
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
        "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping package="com.planet.gametimer.db">

    <class 
        name="Maquina" 
        table="MAQUINAS">
        
        <id 
            name="id" 
            column="ID">
            <generator class="native"/>
        </id>
        
        <property 
            name="nome" 
            column="NOME" 
            not-null="true" 
            unique="true"/>
        
        <property 
            name="preco1" 
            column="PRECO1" 
            not-null="true"/>
            
        <property 
            name="preco2" 
            column="PRECO2" 
            not-null="true"/>
        
        <property 
            name="bonus" 
            column="BONUS"/>
    </class>
    
</hibernate-mapping>

/*
=========================Teste.java=================
 */
package com.planet.teste;

import java.util.List;
import com.planet.gametimer.db.dao.MaquinaDAO;

/**
 * @author Bonomo
 */

public class Teste {

	public static void main(String[] args) {
		try {
			for (int i=0; i<55; i++)
			{
				List maquina = new MaquinaDAO().findAll();
				System.out.println("Consulta ==> " + (i+1));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("Error");
		}
	}
}

Suggested fix:
They repair that in the Loop in the method main I placed 51 iterations.  However I could place 1000 and I would have to function, therefore I am closing the sessions.  Please, esotu needing aid with this, therefore I do not have more idea of as to resolve this.
[27 May 2005 14:47] Esley Bonomo
They forgive me, I forgot to post script of creation of the table.

CREATE TABLE `maquinas` 
(
	`ID` INTEGER (10) UNSIGNED  NOT NULL  AUTO_INCREMENT , 
	`NOME` varchar (45) NOT NULL , 
	`PRECO1` FLOAT (12,31) NOT NULL  DEFAULT 0, 
	`PRECO2` FLOAT (12,31) NOT NULL  DEFAULT 0, 
	`BONUS` varchar (50),
	PRIMARY KEY (ID)
) TYPE=MyISAM
[28 May 2005 6:11] Vasily Kishkin
Sorry...but I could't build your examples. They import a lot of libraries which I don't have ones. Could you please write simpler test case of your problem ?
[28 Jun 2005 23:01] Bugs System
No feedback was provided for this bug for over a month, so it is
being suspended automatically. If you are able to provide the
information that was originally requested, please do so and change
the status of the bug back to "Open".
[9 Mar 2009 11:55] khushwinder Singh
I am using hibernate with mysql.
I am closing all my connections but still i am getting this problem.

In order that the development team can address this error, please report what you were doing that caused this error. 

The following information can help the development team find where the error happened and what can be done to prevent it from happening in the future. 

org.hibernate.exception.JDBCConnectionException: Cannot open connection
	at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:74)
	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
	at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
	at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:420)
	at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
	at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
	at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
	at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
	at net.reumann.demo.persistence.EmployeeHibernateDao.getAllEmployees(EmployeeHibernateDao.java:37)
	at net.reumann.demo.service.EmployeeDaoService.getAllEmployees(EmployeeDaoService.java:25)
	at net.reumann.demo.action.LinkAction.populateEmployees(LinkAction.java:70)
	at net.reumann.demo.action.LinkAction.employee(LinkAction.java:53)
	at sun.reflect.GeneratedMethodAccessor106.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:274)
	at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:194)
	at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419)
	at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224)
	at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
	at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
	at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
	at java.lang.Thread.run(Unknown Source)
Caused by: java.sql.SQLException: Data source rejected establishment of connection,  message from server: "Too many connections"
	at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1018)
	at com.mysql.jdbc.Connection.createNewIO(Connection.java:2572)
	at com.mysql.jdbc.Connection.(Connection.java:1485)
	at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
	at java.sql.DriverManager.getConnection(Unknown Source)
	at java.sql.DriverManager.getConnection(Unknown Source)
	at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
	at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
	... 31 more

I am using the following queries 

"from Employee as e left join fetch e.department d " with each time getting 10 records for pagination as i am having 1,00,000 records in my table.

Please help me to get rid of this problem.
[17 Jul 2009 16:43] Ray Leon
I have the same problem, my application is running on a linux mandriva 2008, hibernate 3.2.1-ga, mysql-5.0.45.0005-1mdv2008.
[17 Jul 2009 23:18] Mark Matthews
It looks/sounds like you're using Hibernate's built-in connection pool in production, which is *not* recommended (from http://docs.jboss.org/hibernate/stable/core/reference/en/html/session-configuration.html#c...)

"Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0."