When reading the MySQL source code, download the source code, write a simple demo, run and report errors
java.sql.SQLException: Error setting driver on UnpooledDataSource. Cause: java.lang.ClassNotFoundException: Cannot find class: com.mysql.jdbc.Driver at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:153) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:145) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:140) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:76) at org.apache.ibatis.demo.MybatisMain.main(MybatisMain.java:36) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
After checking online, most of them are the same as mysql-connector-java-x.x.x-bin.jar, but no matter what version of package I introduce, the problem still exists.
After step-by-step debugging, it is found that the place where the com.mysql.jdbc.driver class is loaded is the following method of org.apache.ibatis.io.classloaderwapper
Class<?> classForName(String name, ClassLoader[] classLoader) throws ClassNotFoundException { for (ClassLoader cl : classLoader) { if (null != cl) { try { return Class.forName(name, true, cl); } catch (ClassNotFoundException e) { // we'll ignore this until all classloaders fail to locate the class } } } throw new ClassNotFoundException("Cannot find class: " + name); }
But why can’t I load it?
So test it in the main method
public class MybatisMain { public static void main(String[] args) throws IOException { try { Class.forName("com.mysql.jdbc.Driver", true, Thread.currentThread().getContextClassLoader()); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
As a result, it still can’t be loaded.
Conclusion:
Look at the POM file
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.24</version> <scope>test</scope> </dependency>
Notice the <scope>test</scope> in the pom file, the problem lies here, comment out this line, the problem is solved.