真正解决方案:java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
1. 故障描述
今天在使用JDK 9.0 环境下使用Hibernate 时候出现了这个错误,错误日志如下:
2. 故障原因分析
JAXB API是java EE 的API,因此在java SE 9.0 中不再包含这个 Jar 包。
java 9 中引入了模块的概念,默认情况下,Java SE中将不再包含java EE 的Jar包
而在 java 6/7 / 8 时关于这个API 都是捆绑在一起的
3.解决方案
3.1 解决方案一
降低JDK 9 版本到 JDK 6/7/8
3.2 解决方案二(亲测可行)
手动加入这些依赖Jar包
要解决这个问题,我导入了下面这四个Jar包修复成功。
下载上面这些文件和复制他们到libs文件夹下,
添加他们导入到Build Path中
重新运行即可
3.3 解决方案三
Maven项目可添加如下依赖:
<!-- Java 6 = JAX-B Version 2.0 -->
<!-- Java 7 = JAX-B Version 2.2.3 -->
<!-- Java 8 = JAX-B Version 2.2.8 -->
<dependencies>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
Gradle 项目引入依赖:
dependencies {
// JAX-B dependencies for JDK 9+
implementation "javax.xml.bind:jaxb-api:2.3.0"
implementation "com.sun.xml.bind:jaxb-core:2.3.0"
implementation "com.sun.xml.bind:jaxb-impl:2.3.0"
implementation "javax.activation:activation:1.1.1"
}
Tips:
建议使用中心仓库,否则可能某些jar找不到:
HTTP: http://repo1.maven.org/maven2
HTTPS:https://repo1.maven.org/maven2
测试代码:
public class DatabaseConnectionTools {
private static final SessionFactory ourSessionFactory;
static {
try {
Configuration configuration = new Configuration();
configuration.configure();
ourSessionFactory = configuration.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession() throws HibernateException {
return ourSessionFactory.openSession();
}
public static void main(final String[] args) throws Exception {
final Session session = getSession();
try {
System.out.println("querying all the managed entities...");
final Metamodel metamodel = session.getSessionFactory().getMetamodel();
for (EntityType<?> entityType : metamodel.getEntities()) {
final String entityName = entityType.getName();
final Query query = session.createQuery("from " + entityName);
System.out.println("executing: " + query.getQueryString());
for (Object o : query.list()) {
System.out.println(" " + o);
}
}
} finally {
session.close();
}
}
}
Tips: 如果做完上述操作,仍然报错,请检查out 文件夹下的lib 文件夹中是否包含刚添加的几个Jar包,如果没有,那么请继续下面的操作:
选中project,然后右键选择open module settings
然后检查Problem选项卡,检查右侧是否有‘Fixed’ 字样,如果有,请点击’Fixed’