何时从连接池获取/返回连接?

时间:2013-08-19 14:53:09

标签: jpa eclipselink connection-pooling

我有一个使用JPA(EclipseLink)的简单Java SE应用程序。默认情况下,我有one 'default' connection pool,最多允许32 connections

假设我做了类似的事情:

EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("myPU");

//read
EntityManager em = emFactory.createEntityManager();

TypedQuery<Entity.class> q = em.createQuery("Select e from Entity e", Entity.class);
List<Entity> entities = q.getResultList();

em.close();

//write
em = emFactory.createEntityManager();

Entity e = new Entity();
em.getTransaction().begin();
em.persist(e);
em.getTransaction().commit();

em.close();
  • 何时从连接池实际请求连接以及何时再次释放它们?
  • 一个查询是否可以请求来自池的多个连接?
  • 如果我将最大连接数从32设置为1,会有区别吗?

1 个答案:

答案 0 :(得分:2)

好吧,我不知道EclipseLink是如何工作的,但是在Hibernate中你可以设置连接释放策略来释放与池的连接:statement,transaction,entity_close,auto。 link但是我找不到EclipseLink这样的东西所以我假设EclipseLink发布连接策略在entity_close之后。

所以,就像这样:

EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("myPU");

//read
EntityManager em = emFactory.createEntityManager();

TypedQuery<Entity.class> q = em.createQuery("Select e from Entity e", Entity.class);
List<Entity> entities = q.getResultList(); << TAKE FROM POOL

em.close(); << RELEASE

//write
em = emFactory.createEntityManager();

Entity e = new Entity();
em.getTransaction().begin(); << TAKE FROM POOL
em.persist(e);
em.getTransaction().commit();

em.close(); << RELEASE