今天一個同事需要在項目中使用Hibernate,於是就推薦了他去閱讀Hibernate的官方文檔。因為這個文檔不但有中文,而且還包含了一個比較詳細的Tutorial。
可是當一切都配置以後,使用JUnit測試時,出現了問題:
org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1542) at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:1035) ... Caused by: org.dom4j.DocumentException: Connection timed out: connect Nested exception: Connection timed out: connect at org.dom4j.io.SAXReader.read(SAXReader.java:484) at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1532) ... 32 more
很是奇怪,因為hibernage.cfg.xml設定檔是從Tutorial中直接copy過來的,只是改了資料庫的驅動、方言和串連。也Google了一些情況出來,很多是由於DTD的版本和設定檔的版本不對導致的。不過在我們這裡不存在這個情況。不過可以判定是由於DTD引起的問題,忽然想起來前一段時間伺服器上一個程式由於不能串連網路,而導致Springframework不能載入的問題,就判斷也可能是因為網路的問題,不能下載“http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd”(儘管我們已經把DTD下載到了本地)。
這時候還好有一段以前可以啟動並執行程式,拿來一看恍然大悟,還果真是DTD的問題。那個設定檔裡引用的是:“http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”,不是一個地址。替換後,問題就解決了。
官方文檔也害人呀。
總結:
問題現象:載入Hibernate時出現異常,可以看到異常資訊:
org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml
Caused by: org.dom4j.DocumentException: Connection timed out: connect Nested exception: Connection timed out: connect
原因:hibernate.cfg.xml中引用了錯誤的DTD檔案路徑“http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd”。
解決方案:替換為正確的DTD路徑:“http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”。