membersound
membersound

Reputation: 86627

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?

Upvotes: 9

Views: 3768

Answers (1)

alextunyk
alextunyk

Reputation: 799

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.

Upvotes: 16

Related Questions