一、报错问题
Caused by: java.lang.ClassNotFoundException: Could not load requested class : com.mysql.jdbc.Driver
二、问题背景
新建Java项目,并添加 Hibernate 框架支持,启动测试(运行默认的Main类中的main()方法),出现报错。
Main.java
import org.hibernate.HibernateException;
import org.hibernate.Metamodel;
import org.hibernate.query.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import javax.persistence.metamodel.EntityType;
import java.util.Map;
public class Main {
private static final SessionFactory ourSessionFactory;
static {
try {
Configuration configuration = new Configuration();
configuration.configure();
ourSessionFactory = configuration.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession() throws HibernateException {
return ourSessionFactory.openSession();
}
public static void main(final String[] args) throws Exception {
final Session session = getSession();
try {
System.out.println("querying all the managed entities...");
final Metamodel metamodel = session.getSessionFactory().getMetamodel();
for (EntityType<?> entityType : metamodel.getEntities()) {
final String entityName = entityType.getName();
final Query query = session.createQuery("from " + entityName);
System.out.println("executing: " + query.getQueryString());
for (Object o : query.list()) {
System.out.println(" " + o);
}
}
} finally {
session.close();
}
}
}
项目结构如下图所示:
三、原因分析
缺少mysql对应版本的驱动包。
四、解决方案
步骤1:去官网下载对应版本的驱动,然后解压得到jar包(本文以下载5.1.47版本为例)
官网下载对应版本的驱动(jar包)地址:https://downloads.mysql.com/archives/c-j/
下载后的文件:mysql-connector-java-5.1.47.zip
解压文件,得到jar包:mysql-connector-java-5.1.47.jar
步骤2:将 jar 包导入项目
选择 mysql-connector-java-5.1.47.jar,如下图所示。
添加 mysql-connector-java-5.1.47.jar 之后,如下图所示。然后点击“OK”按钮即可。