---
title: "hibernate在不联网时不能解析配置文件解决方案"
author: "拳拳天下"
date: "2015-02-03T22:23:01Z"
tags: []
categories: ["互联网"]
slug: "hibernate"
draft: false
lastmod: "2015-02-03T22:23:01Z"
id: 2183151
url: "https://smiling8866.iteye.com/blog/2183151"
---

转载至博客园

在做项目时通常用hibernate框架来进行数据库的一些操作，但是有时候网络条件差或者不联网的情况下，在对数据库进行增删改查操作时，总是会报下面的异常：

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
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
```

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

之前在做时没在意这些，后来通过查了一些资料，才知道了问题出现的原因所在。

我们可以看一下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**文件：

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
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">
```

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

这时无论在联网或者非联网环境下使用hibernate时，其都会去你指定的路径去找对应的dtd，而不会去hibernate的官网去找对应的dtd，这样就不好再出现上面的xml无法解析的异常了。