我有一个方法将记录插入Postgres DB并返回为所述记录生成的标识字段.问题是,如果我在我的POM文件中包含Redshift驱动程序,那么该驱动程序将被使用而不是Postgres驱动程序 – 并且Redshift驱动程序不允许返回标识值.
代码是:
try {
Class.forName( "org.postgresql.Driver" ).newInstance();
Connection connection = DriverManager.getConnection( "jdbc:postgresql://localhost:5433/postgres", "postgres", "password" );
Statement stmt = connection.createStatement();
stmt.execute( "insert into public.job ( job_name ) values ( 'test' )" , Statement.RETURN_GENERATED_KEYS );
ResultSet keyset = stmt.getGeneratedKeys();
if ( keyset.next() ) System.out.println( keyset.getLong( 1 ) );
}
catch ( Exception e ) {
e.printstacktrace();
}
使用此POM时,它可以工作:
<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1201-jdbc41</version>
</dependency>
</dependencies>
使用此POM时,它不起作用:
<dependencies>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>redshift.jdbc</artifactId>
<version>1.1.2.0002</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1201-jdbc41</version>
</dependency>
</dependencies>
是什么让Java选择Redshift驱动程序而不是Postgres驱动程序?
(Redshift驱动程序的类路径是com.amazon.jdbc41.Driver,所以我不认为这是类路径冲突)
TIA
解决方法:
您的问题是,Java支持JDBC 4.0的ServiceLoader机制.
在JDBC 4中,DriverManager将在其jar文件中的meta-inf / services / java.sql.Driver设置中查找并注册驱动程序.当您调用getConnection()时,DriverManager将为给定的jdbc URL选择第一个合适的驱动程序.
现在redshift和postgres驱动程序在jdbc url方面有所不同,但是(引用来自redshift docs http://docs.aws.amazon.com/redshift/latest/mgmt/configure-jdbc-connection.html#obtain-jdbc-url):
A JDBC URL specified with the former format of jdbc:postgresql://endpoint:port/database will still work.
现在,发生的事情是,来自redshift的JDBC驱动程序被加载到服务条目上,并将自己作为redshift jdbc URL和postgres的驱动程序.
我无法准确判断DriverManager是否允许通过加载另一个驱动程序来覆盖现有的jdbc-driver-links,但是问题的解决方案可能是显式控制要么首先加载postgres驱动程序(如果URL只能注册一次),要么显式控制在redshift驱动程序之后加载它(如果可以覆盖JDBC URL映射).
我不知道,是否有一个属性禁止redshift驱动程序注册postgres URL.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。