0

I create only one session factory for the whole progamm and create everytime i want to persist/update/query smth. an new entity manager but i get always an to many connection error. Can anybody give me an adivce? In my point of view it cant be the best solution to increase the number of allowed connections in MySql. I used C3P0 for pooling.

Aruscher
  • 153
  • 1
  • 10
  • Do you run `close()` on `EntityManger` when you are done? Could your database server simply be overloaded by something else? – le3th4x0rbot May 14 '13 at 19:14
  • after every persistence and query operation i run close() on the EntityManager Object and the Database Server is local but the max connections from mysql are default. If im increasing the max connection to 500 or smth. else i will get an error in the later execution – Aruscher May 14 '13 at 19:22
  • Increasing the connection limit is a poor solution. I would make sure C3P0 is not trying to allocate a connection pool that is too large for the database. Otherwise, you might try posting some database access code for SO to look at. – le3th4x0rbot May 14 '13 at 19:24
  • Here the main databasecode [Pastebin](http://pastebin.com/dyuQXFcr). Nearly every database operation runs with combination of this code. – Aruscher May 14 '13 at 19:29
  • Your code does not consistently run `close()` on `EntityManager`s. In your try-catch blocks, if an exception is thrown the `em` never gets closed. The `remove()` method does not even *try* to close the em. – le3th4x0rbot May 14 '13 at 19:36

1 Answers1

1

Try using a try-catch-finally template like this whenever calling the EntityManager.

EntityManager em = ... //However you get an em.
try {
    em.getTransaction().begin();

    // ...  Put your persistence code here.

    em.getTransaction().commit();
} catch (Exception ex) {
    em.getTransaction().rollback();
    throw ex;
} finally {
    em.close();
}
le3th4x0rbot
  • 2,493
  • 23
  • 32