在做項目時通常用hibernate框架來進行數據庫的一些操作,但是有時候網絡條件差或者不聯網的情況下,在對數據庫進行增刪改查操作時,總是會報下面的異常:
Exception in thread "main" org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1418) at org.hibernate.cfg.Configuration.configure(Configuration.java:1352) at org.hibernate.cfg.Configuration.configure(Configuration.java:1338) at org.wjp.hibernate.ExportDB.main(ExportDB.java:8) Caused by: org.dom4j.DocumentException: www.hibernate.org Nested exception: www.hibernate.org at org.dom4j.io.SAXReader.read(SAXReader.java:484) at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1408) ... 3 more
之前在做時沒在意這些,后來通過查了一些資料,才知道了問題出現的原因所在。
我們可以看一下hibernate.cfg.xml文件的開始部分有如下代碼:
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"
而一般的xx.hbm.xml文件的開始部分代碼如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
原因就出現在dtd文件那里,因為hibernate的兩個配置文件分別都會默認去上面兩個加粗的網站去找,所以當使用hibernate進行數據庫操作時,如果你的
網絡環境不好或者沒聯網,此時配置文件無法訪問指定的dtd驗證文件,所以才會出現xml無法解析的異常。
所以解決該問題的方法就是:在需要使用hibernate的項目里,通常在該項目中建立一個文件夾,里面用來存放用於驗證hibernate.cfg.xml的dtd文件和驗證xx.hbm.xml的dtd文件,例如如下代碼,我在我的項目下建立了一個dtd文件夾,里面放了hibernate-configuration-3.0.dtd文件和hibernate-mapping-3.0.dtd文件:
xx.hbm.xml代碼: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "dtd/hibernate-mapping-3.0.dtd"> hibernate.cfg.xml代碼: <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "dtd/hibernate-configuration-3.0.dtd">
這時無論在聯網或者非聯網環境下使用hibernate時,其都會去你指定的路徑去找對應的dtd,而不會去hibernate的官網去找對應的dtd,這樣就不好再出現上面的xml無法解析的異常了。