【问题标题】:Closed connection with ORMLite and MySql与 ORMLite 和 MySql 的封闭连接
【发布时间】:2013-07-16 05:17:57
【问题描述】:

我已经像 ORMLite 文档的示例 7 一样配置了 ORMLite,但过了一会儿我收到连接关闭错误

java.sql.SQLException: Connection has already been closed
at com.j256.ormlite.jdbc.JdbcConnectionSource.getReadWriteConnection   (JdbcConnectionSource.java:177)
at com.j256.ormlite.jdbc.JdbcConnectionSource.getReadOnlyConnection(JdbcConnectionSource.java:168)
at com.j256.ormlite.stmt.StatementExecutor.buildIterator(StatementExecutor.java:228)
at com.j256.ormlite.stmt.StatementExecutor.query(StatementExecutor.java:181)
at com.j256.ormlite.dao.BaseDaoImpl.query(BaseDaoImpl.java:263)
at com.tube.auction.db.DbFacade.createOrUpdateUser(DbFacade.java:265)

我在代码中只使用 dao bean。

<bean id="databaseUrl" class="java.lang.String">
    <constructor-arg index="0" value="jdbc:mysql://localhost:3306/auction" />
</bean>

<bean id="connectionSource" class="com.j256.ormlite.jdbc.JdbcConnectionSource" init-method="initialize">
    <property name="url" ref="databaseUrl" />        
    <property name="username" value="root" />
    <property name="password" value="" />
</bean>
<bean id="userDao" class="com.j256.ormlite.spring.DaoFactory" factory-method="createDao">
    <constructor-arg index="0" ref="connectionSource" />
    <constructor-arg index="1" value="com.tube.auction.dto.User" />
</bean>

如何处理连接关闭问题?我看不到任何强制重新启动连接的方法 例如 注意isOpen() for dao.connection returns true

-- 1. Can i test connection here and restart it? How? Code snippet?
try {
    userDao.queryForId(someUserId);
} catch(SQLException ex) {
   if(is this connection closed?) {
       -- 2. What should I do here to restart connection?
   }
}

【问题讨论】:

  • Max The Cat 你是如何解决这个问题的?

标签: mysql spring ormlite


【解决方案1】:

JdbcConnectionSource 没有内部保持活动机制。 JdbcPooledConnectionSource 产生一个内部线程来执行保活测试。这解决了我的问题。

尝试将 bean 连接源更改为使用JdbcPooledConnectionSource,如下所示:

<bean id="connectionSource" class="com.j256.ormlite.jdbc.JdbcPooledConnectionSource" init-method="initialize">

【讨论】:

    【解决方案2】:

    我认为这是一个常见问题解答。一段时间后,服务器可能会关闭数据库连接,因为它已经有一段时间没有使用或出于其他原因。

    我在这里讨论了在此答案中保持连接打开的方法:

    org.hibernate.exception.GenericJDBCException: could not execute query

    引用,有很多方法可以解决这个问题:

    1. 您可以每隔一段时间对连接发出某种“保持活动”类型的查询(例如:SELECT 1)以保持活动。这假设它因为空闲而关闭。您可以为此使用 ORMLite“原始查询”。
    2. 您可以每隔一段时间重新打开连接。对于 ORMLite,这取决于您使用的连接源类型。
    3. 如果遇到连接关闭异常,则可以重新打开连接。呵呵。
    4. 您可以使用可以为您执行保持活动和重新连接的连接池。 Apache's DBCP 和 HikariCP 是我最喜欢的两个。他们使用 ORMLite。

    查看我的回答了解更多详情。

    【讨论】:

    • 好主意,然而,没有一个能真正解决这个问题。该问题特别提到了如何在 ORMLite 中做到这一点。
    • ORMlite 可与 DBCP 和其他连接池库 @MCToon 一起使用。这是最好的答案。
    猜你喜欢
    • 2012-06-22
    • 2023-03-07
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2020-08-30
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多