赞
踩
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对应版本的驱动包。
官网下载对应版本的驱动(jar包)地址:https://downloads.mysql.com/archives/c-j/
下载后的文件:mysql-connector-java-5.1.47.zip
解压文件,得到jar包:mysql-connector-java-5.1.47.jar
选择 mysql-connector-java-5.1.47.jar,如下图所示。
添加 mysql-connector-java-5.1.47.jar 之后,如下图所示。然后点击“OK”按钮即可。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。