20

I'm trying to retrieve data from a MySQL database through Hibernate, but I'm stuck with this error:

Failed to create sessionFactory object.org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver com.mysql.jdbc.Driver could not be loaded

java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver
[...]

I use a class called DAOFactory to get the hibernate session:

public class DAOFactory {

    private static boolean isInstance = false;  
    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry; 
    private static Session session;

    private DAOFactory() throws ExceptionInInitializerError{        
        if( !isInstance ) {
            try {               
                Configuration cfg   = new Configuration().configure();              
                serviceRegistry     = new ServiceRegistryBuilder().applySettings(cfg.getProperties())
                                                .buildServiceRegistry();
                sessionFactory      = cfg.buildSessionFactory(serviceRegistry);
            } catch (Throwable ex) {
                System.err.println("Failed to create sessionFactory object."+ ex);
                throw new ExceptionInInitializerError(ex);
            }
            session = sessionFactory.openSession();         
            isInstance = true ;
        }               
    }

    public static DAOFactory getInstance() {        
        return new DAOFactory() ;
    }

    public Session getSession() {
        return session ;
    }
}

hibernate.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory name="">
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/enigma</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.pool_size">1</property>
        <property name="current_session_context_class">thread</property>
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
    </session-factory>
</hibernate-configuration>

And mysql-connector-java-5.1.26-bin.jar is already in the classpath:

classpath

Does anyone see what I'm missing ?

Arthur
  • 3,717
  • 7
  • 28
  • 44
  • 7
    Add the jar to your _runtime_ classpath – Reimeus Oct 11 '13 at 13:44
  • If you are working on a web application put the mysql-connector-java-5.1.26-bin.jar under lib folder. – Vaibhav Raj Oct 11 '13 at 13:46
  • possible duplicate of [ClassNotFoundException com.mysql.jdbc.Driver](http://stackoverflow.com/questions/1585811/classnotfoundexception-com-mysql-jdbc-driver) – Eel Lee Oct 11 '13 at 13:46
  • possible duplicate of [MySQL jdbc driver and Eclipse: ClassNotFoundexception com.mysql.jdbc.Driver](http://stackoverflow.com/questions/2353141/mysql-jdbc-driver-and-eclipse-classnotfoundexception-com-mysql-jdbc-driver) – Mark Rotteveel Oct 11 '13 at 13:48
  • I am working on a JPA project, and the 2 previous questions aren't related. But thanks @Reimeus, it was just that. – Arthur Oct 11 '13 at 13:52

7 Answers7

32

Thanks to Reimeus for the answer. mysql-connector-java-5.1.26-bin.jar needs to be in the runtime classpath.

Run -> Run Configurations... -> Classpath -> Add external JAR.

Clean everything, try again, and the Exception is gone.

Arthur
  • 3,717
  • 7
  • 28
  • 44
23

For those who use Maven: add the following dependency in pom.xml.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.17</version>
</dependency>

or choose another version from here.

Then you can get the artifact using:

mvn dependency:resolve

(if you don't use the IDE).

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • Beware that version 6 does not support JDK 1.7 anymore (https://dev.mysql.com/doc/connector-j/6.0/en/connector-j-versions.html) – Joshua H Mar 29 '17 at 18:39
6

Faced the same issue with mysql-connector-java-5.1.48-bin.jar. To fix this issue I changed the driver class name from

<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>

to

<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
Shashanth
  • 4,995
  • 7
  • 41
  • 51
Sagar Trehan
  • 2,401
  • 2
  • 24
  • 32
2

In some cases it can be not a suitable solution to add jar to classpath via Run -> Run Configurations... -> Classpath -> Add external JAR.

First case

When the jar file cannot be put into classpath folder, there is alternative way to load class from the another place. You just need to instantiate URLClassLoader and then invoke loadClass() on it (was mentioned here):

URLClassLoader urlCL = new URLClassLoader(new URL[] {"path_to_jar"});
Class driverClass = urlCL.loadClass("com.mysql.jdbc.Driver");

Second case

If you would like to add your class to classpath at runtime (I prefer the answer of Ranjit Aneesh here), for this purpose you may create a very simple custom class loader extending URLClassLoader with the only overridden addUrl method:

public class DynamicURLClassLoader extends URLClassLoader {

    public DynamicURLClassLoader(URLClassLoader classLoader) {
        super(classLoader.getURLs());
    }

    @Override
    public void addURL(URL url) {
        super.addURL(url);
    }
}

Then invoke it:

URLClassLoader urlCL = (URLClassLoader) ClassLoader.getSystemClassLoader();
new DynamicURLClassLoader(urlCL).addURL("path_to_jar");
Dzmitry Alifer
  • 409
  • 1
  • 6
  • 17
1

Faced the same issue with mysql-connector-java-5.1.48-bin.jar. To fix this issue I changed the driver class name from

com.mysql.cj.jdbc.Driver to

com.mysql.jdbc.Driver

0
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.15</version>
    <scope>provided</scope> 
</dependency>
  • I had above dependency in Maven.
  • The scope tag had caused the error.
  • Removing scope tag solved the problem.
0

Download mysql-connector-java-8.0.20.jar from https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.20/ Add the jar to class path

Run -> Run Configurations... -> Classpath -> Add external JAR.

jyotinadda
  • 51
  • 3