title: How to properly close hibernate session with mysql server
body: <p>I followed the <a href="https://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html/" rel="nofollow">official hibernate tutorial</a> and also several others that describe how to get started with Hibernate (e.g. <a href="http://www.journaldev.com/2934/hibernate-many-to-many-mapping-join-tables-annotation-and-xml-configuration-example" rel="nofollow">Hibernate Many To Many Mapping Join Tables Annotation and XML Configuration Example</a>).</p>
  
  <p>I have a local MySQL Server running under Windows 7 and everything seems to work fine. I can connect using the XML configuration file and Hibernate inserts data into my test database but I cannot properly close the hibernate connection. I get the error message that the connection was not properly closed even if it received the request to do so.</p>
  
  <p>I googled around and saw that many people had that problem a while ago, but could not find any recent information on how to solve the problem.</p>
  
  <p>How is it possible that the official tutorial leads to such a problem? Thank you for anyone of how to suggest of how to tackle this problem.</p>
  
  <p>EDIT: This is the warning messages that I get. There is about a 15s pause between the program printing out the Item2 ID=53 line and the WARNING messages popping up afterwards:</p>
  
  <pre><code>Hibernate: insert into ITEM (item_desc, item_price) values (?, ?)
  Hibernate: insert into ITEM (item_desc, item_price) values (?, ?)
  Hibernate: insert into CART (cart_total) values (?)
  Before committing transaction
  Hibernate: insert into CART_ITEMS (cart_id, item_id) values (?, ?)
  Hibernate: insert into CART_ITEMS (cart_id, item_id) values (?, ?)
  Hibernate: insert into CART_ITEMS (cart_id, item_id) values (?, ?)
  Cart ID=53
  Cart1 ID=54
  Item1 ID=54
  Item2 ID=53
  [WARNING] thread Thread[Abandoned connection cleanup thread,5,com.journaldev.hibernate.main.HibernateManyToManyMain] was interrupted but is still aliv
  e after waiting at least 15000msecs
  [WARNING] thread Thread[Abandoned connection cleanup thread,5,com.journaldev.hibernate.main.HibernateManyToManyMain] will linger despite being asked t
  o die via interruption
  [WARNING] NOTE: 1 thread(s) did not finish despite being asked to  via interruption. This is not a problem with exec:java, it is a problem with the ru
  nning code. Although not serious, it should be remedied.
  [WARNING] Couldn't destroy threadgroup org.codehaus.mojo.exec.ExecJavaMojo$IsolatedThreadGroup[name=com.journaldev.hibernate.main.HibernateManyToManyM
  ain,maxpri=10]
  java.lang.IllegalThreadStateException
          at java.lang.ThreadGroup.destroy(ThreadGroup.java:775)
          at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:328)
          at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
          at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
          at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
          at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
          at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
          at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
          at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
          at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
          at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
          at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
          at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
          at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
          at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
          at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
          at java.lang.reflect.Method.invoke(Method.java:606)
          at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
          at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
          at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
          at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
  [INFO] ------------------------------------------------------------------------
  [INFO] BUILD SUCCESS
  [INFO] ------------------------------------------------------------------------
  [INFO] Total time: 27.936 s
  [INFO] Finished at: 2015-04-28T13:11:56+02:00
  [INFO] Final Memory: 12M/33M
  [INFO] ------------------------------------------------------------------------
  </code></pre>
  
  <p>Here is my hibernate.cfg.xml</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd"&gt;
  &lt;hibernate-configuration&gt;
      &lt;session-factory&gt;
          &lt;property name="hibernate.connection.driver_class"&gt;com.mysql.jdbc.Driver&lt;/property&gt;
          &lt;property name="hibernate.connection.url"&gt;jdbc:mysql://localhost/test&lt;/property&gt;
          &lt;property name="hibernate.connection.username"&gt;test&lt;/property&gt;
          &lt;property name="hibernate.connection.password"&gt;test&lt;/property&gt;        
          &lt;property name="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;
  
          &lt;property name="hibernate.current_session_context_class"&gt;thread&lt;/property&gt;
          &lt;property name="hibernate.show_sql"&gt;true&lt;/property&gt;
  
          &lt;property name="hibernate.c3p0.acquire_increment"&gt;1&lt;/property&gt;
          &lt;property name="hibernate.c3p0.idle_test_period"&gt;100&lt;/property&gt;
          &lt;property name="hibernate.c3p0.max_size"&gt;10&lt;/property&gt;
          &lt;property name="hibernate.c3p0.max_statements"&gt;10&lt;/property&gt;
          &lt;property name="hibernate.c3p0.min_size"&gt;10&lt;/property&gt;
          &lt;property name="hibernate.c3p0.timeout"&gt;100&lt;/property&gt;
  
          &lt;mapping resource="com/journaldev/hibernate/model/cart.hbm.xml" /&gt;
          &lt;mapping resource="com/journaldev/hibernate/model/item.hbm.xml" /&gt;
      &lt;/session-factory&gt;
  &lt;/hibernate-configuration&gt;
  </code></pre>
  
  <p>This is the HibernateUtil that I copied from the manual above:</p>
  
  <pre><code>package com.journaldev.hibernate.util;
  
  import org.hibernate.SessionFactory;
  import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
  import org.hibernate.cfg.Configuration;
  import org.hibernate.service.ServiceRegistry;
  
  public class HibernateUtil {
  
      private static SessionFactory sessionFactory;
  
      private static SessionFactory buildSessionFactory() {
          try {
              // Create the SessionFactory from hibernate.cfg.xml
              Configuration configuration = new Configuration();
              configuration.configure("hibernate.cfg.xml");
              System.out.println("Hibernate Configuration loaded");
  
              ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                      .applySettings(configuration.getProperties()).build();
              System.out.println("Hibernate serviceRegistry created");
  
              SessionFactory sessionFactory = configuration
                      .buildSessionFactory(serviceRegistry);
  
              return sessionFactory;
          } catch (Throwable ex) {
              System.err.println("Initial SessionFactory creation failed." + ex);
              ex.printStackTrace();
              throw new ExceptionInInitializerError(ex);
          }
      }
  
      public static SessionFactory getSessionFactory() {
          if (sessionFactory == null)
              sessionFactory = buildSessionFactory();
          return sessionFactory;
      }
  
  }
  </code></pre>
  
  <p>This is the relevant class that is executed</p>
  
  <pre><code>package com.journaldev.hibernate.main;
  
  import java.util.HashSet;
  import java.util.Set;
  
  import org.hibernate.Session;
  import org.hibernate.SessionFactory;
  import org.hibernate.Transaction;
  
  import com.journaldev.hibernate.model.Cart;
  import com.journaldev.hibernate.model.Item;
  import com.journaldev.hibernate.util.HibernateUtil;
  
  public class HibernateManyToManyMain {
  
      //Saving many-to-many where Cart is primary
      public static void main(String[] args) {
  
          Item iphone = new Item();
          iphone.setPrice(100); iphone.setDescription("iPhone");
  
          Item ipod = new Item();
          ipod.setPrice(50); ipod.setDescription("iPod");
  
          Set&lt;Item&gt; items = new HashSet&lt;Item&gt;();
          items.add(iphone); items.add(ipod);
  
          Cart cart = new Cart();
          cart.setItems(items);
          cart.setTotal(150);
  
          Cart cart1 = new Cart();
          Set&lt;Item&gt; items1 = new HashSet&lt;Item&gt;();
          items1.add(iphone);
          cart1.setItems(items1);
          cart1.setTotal(100);
  
          SessionFactory sessionFactory = null;
          try{
          sessionFactory = HibernateUtil.getSessionFactory();
          Session session = sessionFactory.getCurrentSession();
          Transaction tx = session.beginTransaction();
          session.save(cart);
          session.save(cart1);
          System.out.println("Before committing transaction");
          tx.commit();
          sessionFactory.close();
  
          System.out.println("Cart ID="+cart.getId());
          System.out.println("Cart1 ID="+cart1.getId());
          System.out.println("Item1 ID="+iphone.getId());
          System.out.println("Item2 ID="+ipod.getId());
  
          }catch(Exception e){
              e.printStackTrace();
          }finally{
              if(sessionFactory != null &amp;&amp; !sessionFactory.isClosed()) sessionFactory.close();
          }
  
      }
  
  }
  </code></pre>
  
  <p>I would have expected that the command sessionFactory.close() would properly shutdown and close everything. Here are the versions that I am using with the maven command <code>mvn compile exec:java -Dexec.mainClass=com.journaldev.hibernate.main.HibernateManyToManyMain</code>:</p>
  
  <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
      &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
      &lt;groupId&gt;com.journaldev.hibernate&lt;/groupId&gt;
      &lt;artifactId&gt;HibernateManyToManyMapping&lt;/artifactId&gt;
      &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
  
      &lt;dependencies&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
              &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
              &lt;version&gt;4.3.9.Final&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;mysql&lt;/groupId&gt;
              &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
              &lt;version&gt;5.1.34&lt;/version&gt;
          &lt;/dependency&gt;
          &lt;dependency&gt;
              &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
              &lt;artifactId&gt;hibernate-c3p0&lt;/artifactId&gt;
              &lt;version&gt;4.3.9.Final&lt;/version&gt;
          &lt;/dependency&gt;   
      &lt;/dependencies&gt;
  
  &lt;/project&gt;
  </code></pre>
  
  <p>If anybody could point me to a direction of how to solve this problem, I would be very thankful.</p>
  
  <hr>
  
  <p>New trial with JPADemo.java. I am still having the same problem:</p>
  
  <pre><code>package com.cjg;
  
  import javax.persistence.EntityManager;
  import javax.persistence.EntityManagerFactory;
  import javax.persistence.Persistence;
  
  import com.cjg.Employee;
  
  
  public class JPADemo
  {
          public static void main(String[] args)
      {
                  EntityManagerFactory emf = Persistence.createEntityManagerFactory("cjg-JPA");
                  EntityManager em = emf.createEntityManager();
  
                  em.getTransaction().begin();
                  //Employee employee = new Employee();
                  //employee.setName("Chandan");
                  //System.out.println("COMITTING");
                  //em.persist(employee);
                  em.getTransaction().commit();
                  System.out.println("COMITTING finished");
  
                  em.close();
                  emf.close();
                  //System.out.println("after EntityManager.close()");
  
                  //System.exit(0);
      }
  }
  </code></pre>
  
  <p>relevant part of pom.xml:</p>
  
  <pre><code>&lt;dependency&gt;
      &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
      &lt;artifactId&gt;hibernate-entitymanager&lt;/artifactId&gt;
      &lt;version&gt;4.3.9.Final&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
      &lt;groupId&gt;mysql&lt;/groupId&gt;
      &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
      &lt;version&gt;5.1.35&lt;/version&gt;
  &lt;/dependency&gt;
  </code></pre>
  
  <p>my persistence.xml file:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;persistence xmlns="http://java.sun.com/xml/ns/persistence"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
          version="2.0"&gt;
  
          &lt;persistence-unit name="cjg-JPA"&gt;
              &lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
          &lt;properties&gt;
              &lt;property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" /&gt;
              &lt;property name="hibernate.hbm2ddl.auto" value="create" /&gt;
              &lt;property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /&gt;
              &lt;property name="hibernate.connection.username" value="test" /&gt;
              &lt;property name="hibernate.connection.password" value="test" /&gt;
              &lt;property name="hibernate.connection.url" value="jdbc:mysql://localhost/test" /&gt;
          &lt;/properties&gt;
          &lt;/persistence-unit&gt;
  &lt;/persistence&gt;
  </code></pre>
  
  <p>Am I maybe using an old version of something? I am fairly experienced with programming in general and know how to troubleshoot code but I don't seem to understand the cause of this problem at all. When looking at the connections at the MySQL Server side, I can see that <code>em.close()</code> actually closes the connection. Somehow only the pool is not closed properly. My output is</p>
  
  <pre><code>INFO: HHH000230: Schema export complete
  COMITTING finished
  Mai 01, 2015 1:08:51 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
  INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/test]
  [WARNING] thread Thread[Abandoned connection cleanup thread,5,com.cjg.JPADemo] was interrupted but is still alive after waiting at least 15000msecs
  [WARNING] thread Thread[Abandoned connection cleanup thread,5,com.cjg.JPADemo] will linger despite being asked to die via interruption
  [WARNING] NOTE: 1 thread(s) did not finish despite being asked to  via interruption. This is not a problem with exec:java, it is a problem with the ru
  nning code. Although not serious, it should be remedied.
  [WARNING] Couldn't destroy threadgroup org.codehaus.mojo.exec.ExecJavaMojo$IsolatedThreadGroup[name=com.cjg.JPADemo,maxpri=10]
  java.lang.IllegalThreadStateException
          at java.lang.ThreadGroup.destroy(ThreadGroup.java:775)
          at org.codehaus.mojo.exec.ExecJavaMojo.execute(ExecJavaMojo.java:328)
          at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
          at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
          at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
          at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
          at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
          at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
          at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
          at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
          at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
          at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
          at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
          at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
          at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
          at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
          at java.lang.reflect.Method.invoke(Method.java:606)
          at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
          at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
          at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
          at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
  </code></pre>
  
  <p>Thank you and have a nice weekend. Stephan</p>