More Hibernate JPA troubles
When running JPA together with Grails (not tested on it’s own), with a Hibernate ORM either Hibernate, or with a pool the pool (c3p0), runs out of connections. The architecture of Reposita has a Grails frontend with a (Java) JPA backend to enable switching the frontend and backend independently. The MySQL database barks about to many connections. I do some persist() calls to the database, I guess around 50. Each call gets an EntityManager, does a transaction and closes the EM. Shouldn’t closing the EM close the connection and return it to the pool? Or is this a problem together with Grails, which also runs Hibernate to a MySQL database? Any ideas? I’ve run out of mine.
Update: I’m not sure what I’m doing wrong,
em = getEntityManager(); em.getTransaction().begin(); em.persist(entity); em.getTransaction().commit(); ... em.close();
should work. But even when using with c3p0 as a pool, when calling this code several times, the connection count to the database increases until it reaches the limit, where the MySQL database barks about too many connections.
This might be caused by create-drop of my testing setup.
Update 2: As Dirk pointed out, of course em.close() should go into a finally block and I might add there should be some exception handling and rollback() action.
You can leave a Reply here. Of course, you should follow me on twitter here.


I assume putting things in try-finally blocks would be needed to assure your call to em.close() is effected even in case of Exceptions. It’s a typical case of resource management. See Groovy in Action (http://groovy.canoo.com/gina) section 5.2.2.
BTW: last weeks GrailsExchange has shown me that the Radeox plugin for Grails is used in some of the popular Grails apps :-)