天天看點

Hibernate用Mysql資料庫時連結關閉異常的解決

在一個項目中,客戶要求除作業系統外全部使用免費軟體,是以我使用了Mysql 4.0作為資料庫伺服器,其JDBC驅動為3.0.9版本,在給客戶安裝後調試一切正常。可是到了第二天,隻要一登入就提示“No operations allowed after connection closed”異常,顯示在浏覽器上。在經過一番檢查後我發現,在這種情況下隻要重新啟動Tomcat就恢複正常,然而到了第二天問題依舊。

<b></b>

MySQL closes connections after 8 hours of inactivity. You either need to use a connection pool that handles stale connections or use the "autoReconnect" parameter (see "Developing Applications with MySQL Connector/J").

Also, you should be catching SQLExceptions in your application and dealing with them, rather than propagating them all the way until your application exits, this is just good programming practice. MySQL Connector/J will set the SQLState (see java.sql.SQLException.getSQLState() in your APIDOCS) to "08S01" when it encounters network-connectivity issues during the processing of a query. Your application code should then attempt to re-connect to MySQL at this point.

在客戶那邊,晚上時間是不會有人使用這個系統的,就造成了系統中原先沒有考慮到的這個情況。

以前對Hibernate警告不要使用内置連接配接池作産品用途沒有太放在心上,這次是一個教訓,是以不論從穩定還是性能的考慮,都應該選擇相對更加成熟的連接配接池。

update:除了連接配接池的原因,原先寫的HibernateDAO類也有問題,在有些情況下一個session會被多個請求反複使用,現在已改正。另外,c3p0這個名字不是星球大戰裡那個機器人麼?