Maven+Hibernate+MySQL项目出现javax/xml/bind/JAXBException类未找到错误
解决
java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException异常 异常原因
JDK 9及以上版本移除了javax.xml.bind模块,你使用的Hibernate 5.0.1.Final属于较老版本,依赖该模块,因此在JDK 20环境下运行时会触发类找不到的错误。
解决方案
1. 添加JAXB依赖到pom.xml
在<dependencies>节点中加入以下依赖,手动引入JDK9+移除的JAXB相关模块:
<dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.3.1</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.3.0.1</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency>
2. 修正pom.xml的编译版本配置
你的pom.xml存在拼写错误(maven.compiler.sourse应为maven.compiler.source),且编译版本与实际使用的JDK20不匹配,修正如下:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>20</maven.compiler.source> <maven.compiler.target>20</maven.compiler.target> <hibernate-version>5.0.1.Final</hibernate-version> </properties>
3. 推荐升级Hibernate版本(可选但更稳妥)
Hibernate 5.0.x对JDK11+的支持有限,推荐升级到兼容JDK20的5.6.x系列(最后一个支持JDK8+的5.x分支),修改pom.xml中的Hibernate版本:
<hibernate-version>5.6.15.Final</hibernate-version>
同时,Hibernate 5.6.x构建SessionFactory的方式更简洁,可简化HibernateSessionFactoryUtil类:
import org.example.MessegesEntity; import org.example.ThemeEntity; import org.example.UsersEntity; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateSessionFactoryUtil { private static SessionFactory sessionFactory; private HibernateSessionFactoryUtil() {} public static SessionFactory getSessionFactory() { if (sessionFactory == null) { try { sessionFactory = new Configuration() .configure() .addAnnotatedClass(MessegesEntity.class) .addAnnotatedClass(UsersEntity.class) .addAnnotatedClass(ThemeEntity.class) .buildSessionFactory(); } catch (Exception e) { System.err.println("初始化SessionFactory失败: " + e.getMessage()); e.printStackTrace(); } } return sessionFactory; } }
4. 修正hibernate.cfg.xml的数据库连接URL
当前URL仅指定了MySQL服务器,未关联具体数据库,补充数据库名称及时区参数:
<property name="connection.url">jdbc:mysql://localhost:3306/你的数据库名称?useSSL=false&serverTimezone=UTC</property>
(替换你的数据库名称为实际创建的数据库名,时区参数可避免MySQL连接时区异常)
内容的提问来源于stack exchange,提问作者doradura
相关产品推荐
相关产品推荐

