简体   繁体   中英

How to cast Jdbc4Connection to PGConnection?

I want to make use of postgres CopyManager like:

CopyManager cp = ((PGConnection) dataSource.getConnection()).getCopyAPI();

As I'm using spring-boot , the datasource is a org.apache.tomcat.jdbc.pool.DataSource , thus the connection a Jdbc4Connection .

Problem: The casting throws the following error:

java.lang.ClassCastException: com.sun.proxy.$Proxy55 cannot be cast to org.postgresql.PGConnection

Also, when I try to cast to a Jdbc4Connection, I get the very same error!

java.lang.ClassCastException: com.sun.proxy.$Proxy55 cannot be cast to org.postgresql.jdbc4.Jdbc4Connection

What can I do?

If you are using javax.sql.DataSource then here is a solution:

if (dataSource.getConnection().isWrapperFor(PGConnection.class)) {
  PGConnection pgConnection = dataSource.getConnection().unwrap(PGConnection.class);
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM