title: Hibernate creates too many connections using @Transactional, how to prevent this?
body: <p>I'm fairly new to Hibernate and PostgreSQL, but so far it's going well, although I'm running into a problem now that I can't solve. I'm getting an error while filling the database on the very first operation (which is one transaction inserting or updating 1000 rows in the database). The error is: </p>
  
  <pre>
  SQL Error: 0, SQLState: 53300
  FATAL: sorry, too many clients already
  Exception in thread "main" org.hibernate.exception.GenericJDBCException: Cannot open connection
  </pre>
  
  <p>This is the important code:</p>
  
  <pre><code>@Repository
  public class PDBFinderDAO extends GenericDAO&lt;PDBEntry&gt; implements IPDBFinderDAO {
      @Override
      @Transactional
      public void updatePDBEntry(Set&lt;PDBEntry&gt; pdbEntrySet) {
          for (PDBEntry pdbEntry : pdbEntrySet) {
              getCurrentSession().saveOrUpdate(pdbEntry);
          }
      }
  }
  </code></pre>
  
  <p>getCurrentSession() is extended from GenericDAO and calls sessionFactory.getCurrentSession().</p>
  
  <p>This is my Hibernate configuration:</p>
  
  <pre><code>&lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&gt;
  &lt;hibernate-configuration&gt;
      &lt;session-factory&gt;
          &lt;!-- Database connection settings --&gt;
          &lt;property name="hibernate.connection.driver_class"&gt;org.postgresql.Driver&lt;/property&gt;
          &lt;property name="hibernate.dialect"&gt;org.hibernate.dialect.PostgreSQLDialect&lt;/property&gt;
          &lt;property name="hibernate.connection.url"&gt;jdbc:postgresql://localhost/PDBeter&lt;/property&gt;
          &lt;property name="hibernate.connection.username"&gt;xxxx&lt;/property&gt;
          &lt;property name="hibernate.connection.password"&gt;xxxx&lt;/property&gt;
  
          &lt;!-- Create or update the database schema on startup --&gt;
          &lt;property name="hbm2ddl.auto"&gt;create&lt;/property&gt;
  
          &lt;!-- Use the C3P0 connection pool provider --&gt;
          &lt;property name="hibernate.c3p0.min_size"&gt;5&lt;/property&gt;
          &lt;property name="hibernate.c3p0.max_size"&gt;20&lt;/property&gt;
          &lt;property name="hibernate.c3p0.timeout"&gt;300&lt;/property&gt;
          &lt;property name="hibernate.c3p0.max_statements"&gt;50&lt;/property&gt;
          &lt;property name="hibernate.c3p0.idle_test_period"&gt;300&lt;/property&gt;
  
          &lt;!-- Disable the second-level cache  --&gt;
          &lt;property name="cache.provider_class"&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt;
  
          &lt;!-- Batch size --&gt;
          &lt;property name="hibernate.jdbc.batch_size"&gt;50&lt;/property&gt;
  
          &lt;!-- this makes sure the more efficient new id generators are being used,
          though these are not backwards compatible with some older databases --&gt;
          &lt;property name="hibernate.id.new_generator_mappings"&gt;true&lt;/property&gt;
  
          &lt;!-- Echo all executed SQL to stdout --&gt;
          &lt;!--
          &lt;property name="hibernate.show_sql"&gt;true&lt;/property&gt;
          --&gt;
          &lt;property name="format_sql"&gt;true&lt;/property&gt;
          &lt;property name="use_sql_comments"&gt;true&lt;/property&gt;
      &lt;/session-factory&gt;
  &lt;/hibernate-configuration&gt;
  </code></pre>
  
  <p>This is my Spring configuration:</p>
  
  <pre><code>&lt;beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="http://www.springframework.org/schema/beans" 
      xmlns:aop="http://www.springframework.org/schema/aop"
      xmlns:context="http://www.springframework.org/schema/context" 
      xmlns:tx="http://www.springframework.org/schema/tx"
      xmlns:task="http://www.springframework.org/schema/task"
      xsi:schemaLocation="
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
          http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"&gt;
  
  
      &lt;context:component-scan base-package="nl.ru.cmbi.pdbeter" /&gt;
  
      &lt;!-- Transaction Manager --&gt;
      &lt;bean id="transactionManager"
          class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt;
          &lt;property name="sessionFactory" ref="sessionFactory" /&gt;
      &lt;/bean&gt;
  
      &lt;tx:annotation-driven /&gt;
  
      &lt;!-- Session Factory --&gt;
      &lt;bean id="sessionFactory"
          class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt;
          &lt;property name="configLocation" value="hibernate.cfg.xml" /&gt;
          &lt;property name="packagesToScan" value="nl.ru.cmbi.pdbeter.core.model.domain" /&gt;
      &lt;/bean&gt;
  
      &lt;!-- Task Executor --&gt;
      &lt;task:annotation-driven /&gt;
  &lt;/beans&gt;
  </code></pre>
  
  <p>I'm not really sure what is going wrong, this should only open one connection every time, and close it afterwards, isn't that what @Transactional is supposed to do? Also, is there an easy way to check how many connections are open at a certain time so that I can check before and after the error how many connections were open?</p>
  
  <p>EDIT: when I check the database nothing has been added, so it can't even make one connection, what is going wrong here?</p>
  
  <p>EDIT: I'm sorry but I already solved it myself. It was a very stupid mistake, there was a very small query using criteria that was executed 1000 times as well, but that one was executed before the transaction, causing it to be executed in 1000 separate transactions/sessions/connections (I think, correct me if I'm wrong!)</p>
  
  <p>EDIT: ok, turns out that didn't solve it at all, cause I needed that small query to see if something was already in the database, and if so, get that object from the database so I could update it's fields/columns/whatever you want to call it.</p>
  
  <p>This is the method in the GenericDAO:</p>
  
  <pre><code>@Override
  public PDBEntry findByAccessionCode(String accessionCode) {
      return (PDBEntry) createCriteria(Restrictions.eq("accessionCode", accessionCode)).uniqueResult();
  }
  </code></pre>
  
  <p>There is a function that builds the mapped objects that isn't in the DAO, since it converts a raw datafile into the database object, so I wanted to keep that out of database operations and only put the saveOrUpdate() within the database module. The problem I have now is that the findByAccessionCode() is being called a 1000 times during the conversion of the raw datafile to the database objects, because I need to check whether a certain piece of data is already present in the database, and if so, get the object from the database instead of making a new one.</p>
  
  <p>Now how would I execute that query a 1000 times inside one connection in this context? I tried making that conversion method that converts the 1000 files @transactional, but that didn't work.</p>
  
  <p>Here's the conversion method:</p>
  
  <pre><code>private void updatePDBSet(Set&lt;RawPDBEntry&gt; RawPDBEntrySet) {
      Set&lt;PDBEntry&gt; pdbEntrySet = new LinkedHashSet&lt;PDBEntry&gt;();
  
      for (RawPDBEntry pdb : RawPDBEntrySet) {
          PDBEntry pdbEntry = pdbEntryDAO.findByAccessionCode(pdb.id);
          if (pdbEntry == null) {
              pdbEntry = new PDBEntry(pdb.id, pdb.header.date);
          }
  
          pdbEntry.setHeader(pdb.header.header);
  
          ExpMethod expMethod = new ExpMethod.Builder(pdbEntry, pdb.expMethod.expMethod.toString()).build();
          if (pdb.expMethod.resolution != null) {
              expMethod.setResolution(pdb.expMethod.resolution);
          }
          if (pdb.expMethod.rFactor != null) {
              expMethod.setRFactor(pdb.expMethod.rFactor.rFactor);
  
              if (pdb.expMethod.rFactor.freeR != null) {
                  expMethod.setFreeR(pdb.expMethod.rFactor.freeR);
              }
          }
  
          if (pdb.hetGroups != null) {
              for (PFHetId hetId : pdb.hetGroups.hetIdList) {
                  HetGroup hetGroup = new HetGroup(pdbEntry, hetId.hetId);
  
                  if (hetId.nAtom != null) {
                      hetGroup.setNAtom(hetId.nAtom);
                  }
  
                  if (hetId.name != null) {
                      hetGroup.setName(hetId.name);
                  }
              }
          }
  
          for (PFChain chain : pdb.chainList) {
              new Chain(pdbEntry, chain.chain);
          }
  
          pdbEntrySet.add(pdbEntry);
      }
  
      pdbFinderDAO.updatePDBEntry(pdbEntrySet);
  }
  </code></pre>
  
  <p>(The pdbFinderDAO.updatePDBEntry(pdbEntrySet) was where I originally thought the problem originated)</p>
  
  <p>EDIT: First of all sorry that I created this new post, I really thought I found the answer, but I'll just continue in this post for further edits.</p>
  
  <p>Ok, now I put all the 1000 findAccessionCode criteria inside the DAO by sending a Set of the raw data files to the DAO so it can retrieve the id's there, then finding them in the database, getting the ones it can find and adding it to a HashMap where the database object is mapped with the reference to the raw data file as key (so I know what raw data belongs to what database entry). This function I made @Transactional like so:</p>
  
  <pre><code>@Override
  @Transactional
  public Map&lt;RawPDBEntry, PDBEntry&gt; getRawPDBEntryToPDBEntryMap(Set&lt;RawPDBEntry&gt; rawPDBEntrySet) {
      Map&lt;RawPDBEntry, PDBEntry&gt; RawPDBEntryToPDBEntryMap = new HashMap&lt;RawPDBEntry, PDBEntry&gt;();
  
      for (RawPDBEntry pdb : rawPDBEntrySet) {
          RawPDBEntryToPDBEntryMap.put(pdb, (PDBEntry) createCriteria(Restrictions.eq("accessionCode", pdb.id)).uniqueResult());
      }
  
      return RawPDBEntryToPDBEntryMap;
  }
  </code></pre>
  
  <p>Still, no success... I get the exact same error, but it does tell me it's the criteria that causes it. Why can't I execute all these 1000 queries within the same connection?</p>
  
  <p>EDIT: Yet another update: I tried adding all the queries 1 by 1, and this worked, slowly, but it worked. I did this on an empty database. Next I tried the same thing but now the database already contained the stuff from the first try, and I got the following error:</p>
  
  <pre>
  Exception in thread "main" org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
  </pre>
  
  <p>I'm guessing this has something to do with the fact that I'm getting the objects (that are already in the database and so have to be updated) within the DAO, then sending references back to the conversion method, then changing their fields, then sending them back to the DAO to make them persistent. Although after googling a bit I found people that had problems with collections in their POJO's with the annotation:</p>
  
  <blockquote>
    <p>@OneToMany(mappedBy = "pdbEntry", cascade = CascadeType.ALL, fetch = FetchType.LAZY)</p>
  </blockquote>
  
  <p>where the cascading caused the problem. Do I have to remove all of these cascades and hardcode the saveOrUpdate() operations for all the different mapped objects? Or has this nothing to do with that error?</p>
  
  <p>And finally: I'm still no closer to figuring out how to do this for 1000 objects at a time.</p>