Java 休眠 - ClassNotFoundException:com.mysql.jdbc.Driver

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19319712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:04:00  来源:igfitidea点击:

Hibernate - ClassNotFoundException: com.mysql.jdbc.Driver

javamysqlhibernatejdbc

提问by Arthur

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

我正在尝试通过 Hibernate 从 MySQL 数据库中检索数据,但我遇到了这个错误:

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:

我使用一个名为 DAOFactory 的类来获取休眠会话:

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:

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.jaris already in the classpath:

并且mysql-connector-java-5.1.26-bin.jar已经在类路径中:

classpath

类路径

Does anyone see what I'm missing ?

有没有人看到我错过了什么?

采纳答案by Arthur

Thanks to Reimeus for the answer. mysql-connector-java-5.1.26-bin.jarneeds to be in the runtimeclasspath.

感谢 Reimeus 的回答。mysql-connector-java-5.1.26-bin.jar需要在运行时类路径中。

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

运行 -> 运行配置... -> 类路径 -> 添加外部 JAR。

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

清理所有内容,再试一次,异常消失了。

回答by ROMANIA_engineer

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

对于使用Maven 的人:在 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).

(如果您不使用 IDE)。

回答by Dzmitry Alifer

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

在某些情况下jarclasspath通过Run -> Run Configurations... -> Classpath -> Add external JAR 添加它可能不是一个合适的解决方案。

First case

第一种情况

When the jarfile cannot be put into classpathfolder, there is alternative way to load class from the another place. You just need to instantiate URLClassLoaderand then invoke loadClass()on it (was mentioned here):

jar文件不能放入classpath文件夹时,有另一种方法从另一个地方加载类。你只需要实例化URLClassLoader然后调用loadClass()它(这里提到):

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 classpathat runtime (I prefer the answer of Ranjit Aneeshhere), for this purpose you may create a very simple custom class loader extending URLClassLoaderwith the only overridden addUrlmethod:

如果你想你的类添加到classpath在运行时(我喜欢的答案兰吉特Aneesh这里),为此目的可以创建扩展非常简单的自定义类加载器的URLClassLoader,唯一重写的addUrl方法:

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");

回答by Nirmal Seneviratne

<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.
  • 我在 Maven 中有上述依赖。
  • 范围标签导致了错误。
  • 删除范围标签解决了这个问题。

回答by Sagar Trehan

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

面对同样的问题mysql-connector-java-5.1.48-bin.jar.为了解决这个问题,我改变了驱动程序类名称

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

to

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