[英]Casting java.sql.Connection to com.mysql.jdbc.Connection
My database uses MySQL and I'm using hibernate as an ORM framework. 我的数据库使用MySQL,我使用hibernate作为ORM框架。 I have one instance where I need to access the MySQL
Connection
object. 我有一个实例,我需要访问MySQL
Connection
对象。 I use the following code to get a java.sql.Connection
object: 我使用以下代码来获取
java.sql.Connection
对象:
getHibernateTemplate().getSessionFactory().getCurrentSession().connection();
However, when I try to cast it to a ( com.mysql.jdbc.Connection
) object, I get the following exception: 但是,当我尝试将其
com.mysql.jdbc.Connection
转换为( com.mysql.jdbc.Connection
)对象时,我得到以下异常:
java.lang.ClassCastException: $Proxy50 cannot be cast to com.mysql.jdbc.Connection
Strangely, if I do conn.getClass().getName()
, the class type returned is '$Proxy50' and not 'java.sql.Connection' or some other meaningful type. 奇怪的是,如果我执行
conn.getClass().getName()
,返回的类类型是'$ Proxy50'而不是'java.sql.Connection'或其他一些有意义的类型。
What is the correct method for obtaining a vendor specific Connection
object from Hibernate? 从Hibernate获取供应商特定的
Connection
对象的正确方法是什么? (I'm trying to read a MySQL system property). (我正在尝试读取MySQL系统属性)。 Why does my above example not work?
为什么上面的例子不起作用?
As a rule, you should not need to access the concrete Connection
implementation. 通常,您不需要访问具体的
Connection
实现。
But if you really, really need to, here's an explanation: $Proxy40 means it is a JDK dynamic proxy. 但如果你真的,真的需要,这里有一个解释:$ Proxy40意味着它是一个JDK动态代理。 Spring tends to create these.
Spring倾向于创造这些。 If yours is created by spring, then, you can get the real object by:
如果你的是春天创造的,那么你可以通过以下方式获得真实的物体:
Advised advised = (Advised) connection;
Connection conn = (Connection) advised.getTargetSource().getTarget();
If spring is not involved in the proxying, you should be able to call Connection.unwrap(..)
as BalusC suggested (you should be able to to that either way) 如果代理中没有涉及spring,你应该可以像BalusC建议的那样调用
Connection.unwrap(..)
(你应该能够以任何一种方式)
What is the correct method for obtaining a vendor specific Connection object from Hibernate?
从Hibernate获取供应商特定的Connection对象的正确方法是什么?
It depends. 这取决于。
I've unwrapped Proxy's successfully like this. 我已经成功解开了Proxy的问题。 How to unwrap the original object from a dynamic proxy
如何从动态代理中解包原始对象
Kinda scary stuff though, avoid it if you can. 有点可怕的东西,如果你可以避免它。
com.mysql.jdbc.Connection
implements java.sql.Connection
interface. com.mysql.jdbc.Connection
实现了java.sql.Connection
接口。 Therefore when you create com.mysql.jdbc.Connection
object is also java.sql.Connection
object. 因此在创建
com.mysql.jdbc.Connection
对象时也是java.sql.Connection
对象。 So you cannot cast operation there because returning object is java.sql.Connection
not com.mysql.jdbc.Connection
. 所以你不能在那里执行操作,因为返回的对象是
java.sql.Connection
而不是com.mysql.jdbc.Connection
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.