1. Overview
The Java Database Connectivity (JDBC) Application Programming Interface (API) provides a set of classes and interfaces. We can use these to develop applications to connect to data sources such as relational databases and process data. Further, we need a database-specific JDBC Driver that implements this API to connect to the specific database.
When connecting to the MySQL database using JDBC we could encounter the exception message java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver. When we use the previous, now deprecated class com.mysql.jdbc.Driver, we could get the message java.lang.ClassNotFoundException: com.mysql.jdbc.Driver.
In this tutorial, we’ll learn how to solve this exception. We don’t need any special setup other than the application development environment we may already use. We’ll discuss solving this exception using JUnit 5 integration tests with Apache Maven as the build tool.
2. Cause of the Exception
We get this exception when the driver manager service that manages and loads JDBC drivers can’t find a driver class needed to obtain a connection. This exception can only occur at run-time. We can request a specific MySQL JDBC driver class to be loaded with the Class.forName(“com.mysql.cj.jdbc.Driver”) call in the application; however, it’s unnecessary because the DriverManager locates and loads a suitable driver by itself at run-time.
However, when the DriverManger doesn’t find a suitable or requested driver class in the classpath, it throws this exception. The classpath is the directory path that the Java Runtime Environment (JRE) searches for classes. To fix this issue, we need to add the MySQL Connector/J binaries or the jar file containing the Connector/J classes to the runtime classpath.
3. Example
A standalone application doesn’t require an application/web server. We can fix this exception by adding the Maven dependency for MySQL Connector/J to the configuration file pom.xml:
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
Let’s use a test class to check if the error is solved. No exception is thrown because we added the driver class and it gets found and loaded:
public class MySQLLoadDriverUnitTest {
@Test
void givenADriverClass_whenDriverLoaded_thenEnsureNoExceptionThrown() {
assertDoesNotThrow(() -> {
Class.forName("com.mysql.cj.jdbc.Driver");
});
}
}
4. Conclusion
In this article, we learned how to fix the java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver exception problem. We used a JUnit 5 unit test developed in a Maven project to demonstrate adding MySQL Connector/J to the runtime classpath to fix the exception.
As always, the sample scripts used in this article are available over on GitHub.