gpt4 book ai didi

java - hibernate - ClassNotFoundException : com. mysql.jdbc.Driver

转载 作者:IT老高 更新时间:2023-10-28 23:53:46 33 4
gpt4 key购买 nike

我正在尝试通过 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
[...]

我使用一个名为 DAOFactory 的类来获取 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>

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

classpath

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

最佳答案

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

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

清理一切,再试一次,异常就消失了。

关于java - hibernate - ClassNotFoundException : com. mysql.jdbc.Driver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19319712/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com