This is my code (it’s JAX-RS + JPA):
@Path("/")
public class Foo {
private static final EntityManagerFactory FACTORY =
Persistence.createEntityManagerFactory("foo");
@POST
public void save(String name) {
EntityManager em = this.FACTORY.createEntityManager();
EntityTransaction trans = em.getTransaction();
trans.begin();
MyEntity entity = new MyEntity();
em.persist(entity);
em.flush();
trans.commit();
em.close();
}
}
I’m using OpenJPA 1.2.2. Connections to MySQL are never got closed and in some time I see “too many connections”. What is wrong with this design?
What happens in your code in the event of errors? Are you guaranteed to reach the em.close() line? Are you seeing occasional exceptions, perhaps caught elsewhere?
Put your tidy-up code in finally blocks so that they are guaranteed to be run.
See this link for an explanation.