数据库驱动程序类动态加载 [英] Database driver-class dynamic loading

查看:90
本文介绍了数据库驱动程序类动态加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Java开发与数据库无关的应用程序。我选择了休眠作为ORM。 jdbc的问题在于,它只是一个接口,我们需要在类路径中提供db的驱动程序类。由于数据库应该是可配置的,因此我必须动态加载数据库的驱动程序类。 (用户应将驱动程序类保存在一个文件夹中,并且应动态加载它)
下面是我的代码。

I want to develop a DB-Agnostic application in java. I have chosen hibernate as ORM. The problem with jdbc is that , it is just an interface and we need the driver class of the db in the class path. Since the database should be configurable i have to go for loading the driver class of DB dynamically. (User should keep the driver class in a folder and it should be loaded dynamically ) Below is my code.

File driverJar = new File("E:\\Jomon\\backup_2017_05_25\\2.2\\WS\\2.2_1\\lib\\Drivers\\postgresql-42.1.1.jar");
URL[] urls = new URL[] { driverJar.toURL() };
URLClassLoader classLoader = new URLClassLoader(urls,DBUtils.class.getClassLoader());
Class.forName("org.postgresql.Driver", true, classLoader);

到目前为止没有错误。
但是在此之后,在初始化休眠连接时,出现错误java.lang.ClassNotFoundException:org.postgresql.Driver。

No error till now. But after this, while initializing hibernate connection, I am getting error java.lang.ClassNotFoundException: org.postgresql.Driver.

我可以知道什么是

推荐答案

最后,我自己得到了解决方案,
这里的问题是,我创建了一个新的

Finally I got the solution by myself, The problem here is , I have created a new classloader and loaded the jar into it.

休眠在系统类加载器中搜索驱动程序类,而不是在用户定义的类加载器中搜索。

The hibernate is searching for driver class in system class loader , not in the user defined class loaders.

可以通过将jar加载到系统类加载器中来解决这里的问题,如下所示。

The problem here can be solved by load the jar into system class loader as below.

File driverJar = new File("E:\\Jomon\\backup_2017_05_25\\2.2\\WS\\2.2_1\\lib\\Drivers\\postgresql-42.1.1.jar");
URL myJarFile = new URL("jar", "", "file:" + driverJar.getAbsolutePath() + "!/");
URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

Class sysClass = URLClassLoader.class;
Method sysMethod = sysClass.getDeclaredMethod("addURL", new Class[] { URL.class });
sysMethod.setAccessible(true);
sysMethod.invoke(sysLoader, new Object[] { myJarFile });

Class.forName("org.postgresql.Driver", true, classLoader); // Now no error in this line.

这篇关于数据库驱动程序类动态加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆