zoukankan      html  css  js  c++  java
  • hibernate在不联网时不能解析配置文件解决方案

    在做项目时通常用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无法解析的异常了。

  • 相关阅读:
    appium+python自动化测试之webview的处理。
    Mysql为什么要使用视图
    show status 查看各种状态
    MySQL show processlist
    Java爬虫系列(五)
    div p、div>p、div+p、div~p、div.a 、p,span的用法和区别
    Spring Boot 定时任务 -- @Scheduled
    设计模式
    12月15日总结
    成员变量和静态变量的区别
  • 原文地址:https://www.cnblogs.com/xiaoluo501395377/p/2756204.html
Copyright © 2011-2022 走看看