一、问题出现
初次使用Maven配置Mybatis项目环境,在测试mysql数据库连接时出现了异常
Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.sql.SQLException: Error setting driver on UnpooledDataSource. Cause: java.lang.ClassNotFoundException: Cannot find class: com.mysql.jdbc.Driver
查询资料后,得知是Mybatis XML配置文件出了问题
二、问题解决
此时,我的pom.xml配置如下所示:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>top.wenzhao18</groupId>
<artifactId>MavenMabaitsTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MavenMabaitsTest</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- mybatis maven环境搭建 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
</dependencies>
</project>
上网检索了一番后,发现可能是mysql数据库驱动版本的冲突/不兼容问题,于是将mysql依赖版本
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
修改为8.0.15
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
再次运行,发现还是有报错
### Error querying database. Cause: java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
这时,修改Mybatis XML配置文件dataSource中的url属性,在其后添加?serverTimezone=GMT,即将mysql的时区设置为美国时间,如图所示:

此时再运行程序,发现已经能成功连接数据库了。

三、问题总结
初次使用Maven配置Mybatis项目报了这个异常,排错检索资料用时一天(一晚上+一个下午),
由此体会到Maven依赖冲突、版本不兼容的可怕支配力量(不)
-
对于
Cannot find class: com.mysql.jdbc.Driver异常的排查,我是首先所锁定异常出现的位置。 -
从
Error setting driver on UnpooledDataSource这句,我们就可以粗略判定是配置文件设置有误,由此可以定位到Mybatis的XML配置文件。 -
而后再看
Cannot find class: com.mysql.jdbc.Driver,对比dataSource下的driver属性,我们可以得知在创建SqlSessionFactory对象解析Mybatis配置文件时,读取driver属性出了问题;而问题的根源就是在lib中找不到mysql的驱动。 -
再回过头检查pom.xml中的mysql依赖,可以大胆猜测是版本的问题。
四、参考文献
MyBatis问题1 java.lang.ClassNotFoundException: Cannot find class: com.mysql.cj.jdbc.Driver
本文记录了在使用Maven配置Mybatis项目时遇到的数据库连接异常问题及解决过程,涉及Maven依赖冲突、版本不兼容等问题,最终通过调整mysql驱动版本和时区配置解决问题。
3968

被折叠的 条评论
为什么被折叠?



