我動態加載驅動程序JDBC。它工作正常,但是這DriverManager
變得無用,當我嘗試打開一個Hibernate會話如何爲Hibernate動態加載驅動程序?
org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver com.mysql.jdbc.Driver could not be loaded
下面是代碼
public class TestHibernateSessionFactory {
public void test() throws MalformedURLException, InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
URL u = new URL("jar:file:/C:\\Users\\...\\mysql-connector-java-5.1.40-bin.jar!/");
String classname = "com.mysql.jdbc.Driver";
URLClassLoader ucl = new URLClassLoader(new URL[] { u });
Driver d = (Driver)Class.forName(classname, true, ucl).newInstance();
DriverManager.registerDriver(new DriverLoader(d));
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306", "admin", "password");
// this is the proof that DriverManager loaded and works fine
System.out.println("CONNECTION OBJECT WORKS FINE: " + con);
// Now I want to try this same technique with hibernate
Session session = null;
Transaction tx = null;
SessionFactory sf = buildSessionFactory("jdbc:mysql://localhost:3306", "admin", "password");
// ERROR Specified JDBC Driver com.mysql.jdbc.Driver could not be loaded WHY ???
session = sf.openSession();
System.out.println(session);
}
private static SessionFactory buildSessionFactory(String myUrl, String myUser, String myPass) {
Configuration configuration = new Configuration();
configuration.configure();
configuration.setProperty("hibernate.connection.url", myUrl);
configuration.setProperty("hibernate.connection.username", myUser);
configuration.setProperty("hibernate.connection.password", myPass);
configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.hbm2ddl.auto", "create-drop");
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
return configuration.buildSessionFactory(serviceRegistry);
}
}
兩個問題:
- 爲什麼它不工作與休眠,但與jdbc?
- 如何解決?
參考https://stackoverflow.com/questions/44346826/database-driver-class-dynamic-loading,看看喬布斯的答案,它可以幫助你 – harshavmb
謝謝。這是一個真正的答案 –