我有一个使用Hibernate JPA
和persistence.xml和EntityManager
<property name="connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider"/>
<!-- Important -->
<property name="hibernate.c3p0.min_size" value="10"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.acquire_increment" value="1"/>
<property name="hibernate.c3p0.minPoolSize" value="1"/>
<property name="hibernate.c3p0.timeout" value="1800"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="3000"/>
我有一个用于处理EntityManager和EntityManagerFactory的EntityManagerHelper类
public class EntityManagerHelper {
static Logger logger = Logger.getLogger(EntityManagerHelper.class);
private static final EntityManagerFactory emf;
private static final ThreadLocal<EntityManager> threadLocal;
static {
logger.warn("Criando EM Factory");
emf = Persistence.createEntityManagerFactory("persistencia");
threadLocal = new ThreadLocal<EntityManager>();
}
public static EntityManager getEntityManager() {
EntityManager em = threadLocal.get();
if (em == null) {
em = emf.createEntityManager();
threadLocal.set(em);
}
return em;
}
public static void closeEntityManager() {
EntityManager em = threadLocal.get();
if (em != null) {
logger.info("fechando Transação");
em.close();
threadLocal.set(null);
}
}
public static void closeEntityManagerFactory() {
logger.warn("Destroindo EM Factory");
emf.close();
}
public static void beginTransaction() {
logger.info("iniciando Transação");
getEntityManager().getTransaction().begin();
}
public static void rollback() {
getEntityManager().getTransaction().rollback();
}
public static void commit() {
logger.info("commitando Transação");
getEntityManager().getTransaction().commit();
}
}
然后我使用此过滤器
public class JPAFilter implements Filter {
@Override
public void destroy() {}
@Override
public void init(FilterConfig fc) throws ServletException {}
@Override
public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
try {
req.setAttribute("EntityManager", EntityManagerHelper.getEntityManager());
EntityManagerHelper.beginTransaction();
chain.doFilter(req, res);
EntityManagerHelper.commit();
} catch (RuntimeException e) {
if ( EntityManagerHelper.getEntityManager() != null && EntityManagerHelper.getEntityManager().isOpen())
EntityManagerHelper.rollback();
throw e;
} finally {
EntityManagerHelper.closeEntityManager();
}
}
public EntityManager getEntityManager(){
return EntityManagerHelper.getEntityManager();
}
}
但座椅未关闭连接,请参见
PostgreSQL
请指出我错了。
谢谢。
答案 0 :(得分:0)
连接池与关闭连接无关。都是相反的情况-保持连接存活并重用它们。保持活动的空闲连接比按需重新建立连接要有效得多。
作为奖励,请检查https://www.mchange.com/projects/c3p0/和附录C,因为您的某些配置属性是多余的和/或没有任何作用。