gpt4 book ai didi

java - 在 Hibernate 3.6.10.Final + c3p0 + struts2 中打开新连接时关闭连接

转载 作者:行者123 更新时间:2023-11-30 04:08:54 31 4
gpt4 key购买 nike

我在使用 hibernate 3.6.10.Final 时遇到问题。我的项目使用struts2+hibernate,我使用创建持久请求

 <dependency>
<groupId>com.googlecode.s2hibernate</groupId>
<artifactId>struts2-fullhibernatecore-plugin</artifactId>
<version>2.2.2-GA</version>
</dependency>

为了登录目的,或者当我生成在请求结束后停止工作的长期线程时,我必须在拦截器中使用标准 hibernate session 。

我对 struts2-fullhibernatecore-plugin 生成的 session 没有问题,但当我尝试在拦截器或无法使用标准 struts2-fullhibernatecore-plugin 逻辑的分离线程内生成简单事务时,我收到奇怪的异常。

给我带来问题的一段代码是包含在拦截器中的

public String intercept(ActionInvocation invocation) throws Exception {
... bla bla ...
userManager.setSession(HibernateUtil.getSessionFactory().openSession());
logger.info("Session status "+ userManager.getSession().isOpen() +" " +userManager.getSession().isDirty());
userManager.setTransaction(userManager.getSession().beginTransaction());
...

当我停止使用它时,我会关闭此 session

当我尝试生成交易时,我的代码崩溃了

 2013-11-21 07:11:09,470 ajp-bio-8009-exec-2 ERROR
(org.apache.struts2.dispatcher.Dispatcher:38) - Exception occurred
during processing request: Cannot open connection
org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:142)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:85)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1463)
at videoshare.interceptor.usermanager.PossibleLoginIterceptor.intercept(PossibleLoginIterceptor.java:49)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:200)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662) Caused by: java.sql.SQLException:
com.mchange.v2.c3p0.PoolBackedDataSource@1638fbc [
connectionPoolDataSource ->
com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@a01f8a5c [
acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay
-> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0,
connectionCustomizerClassName -> null, connectionTesterClassName ->
com.mchange.v2.c3p0.impl.DefaultConnectionTester,
debugUnreturnedConnectionStackTraces -> false, factoryClassLocation ->
null, forceIgnoreUnresolvedTransactions -> false, identityToken ->
z8kfsx8yxnfxily93r0u|f04d94, idleConnectionTestPeriod -> 100,
initialPoolSize -> 10, maxAdministrativeTaskTime -> 0,
maxConnectionAge -> 0, maxIdleTime -> 100,
maxIdleTimeExcessConnections -> 0, maxPoolSize -> 100, maxStatements
-> 10, maxStatementsPerConnection -> 0, minPoolSize -> 10, nestedDataSource ->
com.mchange.v2.c3p0.DriverManagerDataSource@f2778985 [ description ->
null, driverClass -> null, factoryClassLocation -> null, identityToken
-> z8kfsx8yxnfxily93r0u|4f7bc2, jdbcUrl -> jdbc:mysql://localhost/youcabaret, properties -> {user=******,
password=******} ], preferredTestQuery -> null, propertyCycle -> 0,
testConnectionOnCheckin -> false, testConnectionOnCheckout -> true,
unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies ->
false; userOverrides: {} ], dataSourceName -> null,
factoryClassLocation -> null, identityToken ->
z8kfsx8yxnfxily93r0u|1aaf64d, numHelperThreads -> 3 ] has been
closed() -- you can no longer use it.
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.assertCpds(AbstractPoolBackedDataSource.java:447)
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getPoolManager(AbstractPoolBackedDataSource.java:459)
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:128)
at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:78)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
... 26 more 2013-11-21 07:11:24,870 ajp-bio-8009-exec-2 ERROR (org.apache.struts2.dispatcher.Dispatcher:38) - Exception occurred
during processing request: Cannot open connection
org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:142)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:85)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1463)
at videoshare.interceptor.usermanager.PossibleLoginIterceptor.intercept(PossibleLoginIterceptor.java:49)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:200)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662) Caused by: java.sql.SQLException:
com.mchange.v2.c3p0.PoolBackedDataSource@1638fbc [
connectionPoolDataSource ->
com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@a01f8a5c [
acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay
-> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0,
connectionCustomizerClassName -> null, connectionTesterClassName ->
com.mchange.v2.c3p0.impl.DefaultConnectionTester,
debugUnreturnedConnectionStackTraces -> false, factoryClassLocation ->
null, forceIgnoreUnresolvedTransactions -> false, identityToken ->
z8kfsx8yxnfxily93r0u|f04d94, idleConnectionTestPeriod -> 100,
initialPoolSize -> 10, maxAdministrativeTaskTime -> 0,
maxConnectionAge -> 0, maxIdleTime -> 100,
maxIdleTimeExcessConnections -> 0, maxPoolSize -> 100, maxStatements
-> 10, maxStatementsPerConnection -> 0, minPoolSize -> 10, nestedDataSource ->
com.mchange.v2.c3p0.DriverManagerDataSource@f2778985 [ description ->
null, driverClass -> null, factoryClassLocation -> null, identityToken
-> z8kfsx8yxnfxily93r0u|4f7bc2, jdbcUrl -> jdbc:mysql://localhost/youcabaret, properties -> user=******,
password=******} ], preferredTestQuery -> null, propertyCycle -> 0,
testConnectionOnCheckin -> false, testConnectionOnCheckout -> true,
unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies ->
false; userOverrides: {} ], dataSourceName -> null,
factoryClassLocation -> null, identityToken ->
z8kfsx8yxnfxily93r0u|1aaf64d, numHelperThreads -> 3 ] has been
closed() -- you can no longer use it.
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.assertCpds(AbstractPoolBackedDataSource.java:447)
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getPoolManager(AbstractPoolBackedDataSource.java:459)
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:128)
at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:78)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
... 26 more

日志显示

2013-11-21 07:25:13,228 ajp-bio-8009-exec-1 INFO usermanager.PossibleLoginIterceptor intercept - Session status true false so the session seemto be open milliseconds before

我的 hibernate 配置是

    <property name="hibernate.connection.url">jdbc:mysql://localhost/*******</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.username">*******</property>
<property name="hibernate.connection.password">*******</property>
<property name="show_sql">false</property>
<property name="connection.pool_size">10</property>

<!-- configuration pool via c3p0-->
<property name="c3p0.max_size">100</property>
<property name="c3p0.max_statements">10</property>
<property name="c3p0.min_size">10</property>
<property name="c3p0.idle_test_period">100</property><!-- seconds -->
<property name="c3p0.timeout">100</property><!-- seconds -->
<property name="c3p0.testConnectionOnCheckout">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="current_session_context_class">thread</property>

我从这个实用程序类打开连接

package hibernate.manager;

import org.apache.log4j.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import videoshare.manager.videomanager.VideoManager;

public class HibernateUtil {
protected static Logger logger = Logger.getLogger(VideoManager.class
.getName());

private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
logger.error("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

}

我在长期线程中遇到了同样类型的异常,有时一切都很顺利。

为了完成信息,我使用 Apache Tomcat/7.0.47

Java(TM) SE Runtime Environment (build 1.6.0_45-b06)
Java HotSpot(TM) Server VM (build 20.45-b01, mixed mode)

但我在其他系统上也注意到这个问题,所以我认为这是一个配置问题。

最佳答案

在拦截方法中,userManager 对象是在实例级别定义的吗?如果是,则尝试在方法级别实例化它。

由于拦截器仅实例化一次,因此来自多个线程的同时请求可能会导致此问题。这完全取决于拦截器中数据库操作占用的时间;从 session 开幕到 session 闭幕。随着完成数据库操作所用时间的增加,异常风险也会增加。

希望这有帮助。

谢谢。

关于java - 在 Hibernate 3.6.10.Final + c3p0 + struts2 中打开新连接时关闭连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20114214/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com