如何为Hibernate动态加载驱动程序?

时间:2017-05-26 17:40:23

标签: java hibernate jdbc

我正在为JDBC动态加载驱动程序。它工作正常,但是当我尝试打开一个休眠会话时,DriverManager变得无用

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);
    }

    }

两个问题:

  1. 为什么它不适用于hibernate,但适用于jdbc?
  2. 如何解决?

2 个答案:

答案 0 :(得分:1)

答案是Hibernate将尝试从上下文(当前线程)类加载器加载驱动程序,并且它没有驱动程序。第一部分有效,因为您使用具有驱动程序的类加载器来创建连接。

解决方案可能是使用操作上下文类加载器。当使用加载的驱动程序退出的方法时,不要忘记清理它。

答案 1 :(得分:1)

解决问题的方法可能是这样的:

想法是拥有自己的类加载器,并在初始化ClassLoader

之前使用您的Hibernate SessionFactory

像这样:

Thread.currentThread().setContextClassLoader(myOwnClassLoader);

虽然这不是解决问题的最佳解决方案之一,但事实就是如此。虽然this是一个不完整的讨论,但它仍然有用,可以指导您继续。

希望这有帮助!!!