在我的应用程序中,我使用Hibernate和mysql连接数据库。当有来自GUI的请求时,此应用程序连接到数据库。在尝试再次连接到数据库之后,很长一段时间没有来自GUI的请求。我收到以下错误。可能的解决方案是什么?
org.jboss.util.NestedSQLException: You are trying to use a connection factory that has been shut down: ManagedConnectionFactory is null.; - nested throwable:
(javax.resource.ResourceException: You are trying to use a connection factory that has been shut down: ManagedConnectionFactory is null.)
at org.jboss.resource.adapter.jdbc.WrapperDataSource.getConnection(WrapperDataSource.java:95)
at org.hibernate.connection.DatasourceConnectionProvider.getConnection(DatasourceConnectionProvider.java:92)`
这是我的代码连接到数据库。
SessionFactory factory;
factory = new Configuration().configure().buildSessionFactory();
session = factory.openSession();
SessionFactoryImplementor impl = (SessionFactoryImplementor)session.getSessionFactory();
ConnectionProvider cp = impl.getConnectionProvider();
conn = cp.getConnection();//This conn is used for prepared statement and so on..
这是我的mysql ds文件
<datasources>
<local-tx-datasource>
<jndi-name>MySqlDS</jndi-name>
<use-java-context>true</use-java-context>
<url-delimiter>|</url-delimiter>
<connection-url>jdbc:mysql://localhost:3306/TEST_DB?zeroDateTimeBehavior=convertToNull</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>user</user-name>
<password>****</password>
<exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
<new-connection-sql>select current_date()</new-connection-sql>
<check-valid-connection-sql>select current_date()</check-valid-connection-sql>
<min-pool-size>1</min-pool-size>
<max-pool-size>5</max-pool-size>
<set-tx-query-timeout/>
<query-timeout>300</query-timeout>
<metadata>
<type-mapping>mySQL</type-mapping>
</metadata>
</local-tx-datasource>
</datasources>
答案 0 :(得分:0)
你做错了。 Hibernate会话只应在单个事务的生命周期内连接到数据库。完成交易后,您也应该关闭会话。
您可以先定义TransactionCallback:
public interface TransactionCallable<T> {
public abstract T execute(Session session);
}
然后定义一个Helper会话管理方法:
protected <T> T doInTransaction(TransactionCallable<T> callable) {
T result = null;
Session session = null;
Transaction txn = null;
try {
session = sf.openSession();
txn = session.beginTransaction();
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
}
});
result = callable.execute(session);
txn.commit();
} catch (RuntimeException e) {
if ( txn != null && txn.isActive() ) txn.rollback();
throw e;
} finally {
if (session != null) {
session.close();
}
}
return result;
}
因此您甚至可以按照建议运行本机查询:
final String sql = ...;
doInTransaction(new TransactionCallable<Object>() {
Boolean result;
@Override
public Object execute(Session session) {
session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
Statement statement = connection.createStatement();
result = statement.execute(sql);
}
});
return result;
}
});