Hibernate – ClassNotFoundException:com.mysql.jdbc.Driver

我正在尝试通过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会话:

 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中:

     com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/enigma root  org.hibernate.dialect.MySQLDialect 1 thread org.hibernate.cache.NoCacheProvider true update   

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

类路径

有谁看到我错过了什么?

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

运行 – >运行配置… – >类路径 – >添加外部JAR。

清理所有内容,再试一次,Exception就不见了。

对于那些使用Maven的人 :在pom.xml中添加以下依赖项。

  mysql mysql-connector-java 6.0.6  

或者从这里选择其他版本。

然后你可以使用以下方法获取工件:

 mvn dependency:resolve 

(如果您不使用IDE)。