开发者

Why there are "too many connections" in JPA?

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 i开发者_运维百科n 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.


Probably you are using conneciton pool. OpenJPA instead of creating new connection per each db call which is very costly task, takes connection from the pool and once the connection is not needed any more it is returned to the pool. This is mainly for performance reasons i.e. hibernate uses c3p0 connection pool library for that purpose and there is also some other library called dbcp (database connection pool) from Apache which does similar stuff.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜