我在 Glassfish 3.1.2 中创建了一个名为“userdb”的连接池和一个名为“userdbresource”的数据源。创建数据源时,我在管理控制台中将类型指定为“javax.sql.Datasource”。
在我的 REST Web 服务中,我编写了以下代码
DataSource ds = null;
try
{
InitialContext ctx = new InitialContext();
ds = (DataSource) ctx.lookup("userdbresource");
}
catch (NamingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection con = (Connection) ds.getConnection();
Statement stmt=con.createStatement();
我总是在 Connection con = (Connection) ds.getConnection();
我已将以下内容添加到 web.xml
<resource-ref>
<res-ref-name>userdbresource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
但没有变化。在使用 com.mysql.jdbc.Connection 查找连接后,我尝试打开连接。但没有变化。
日志中实际的类转换异常是
java.lang.ClassCastException: com.sun.gjc.spi.jdbc40.ConnectionHolder40 cannot be cast to com.mysql.jdbc.Connection
如果有人知道我需要进行哪些更改才能使用从池中检索的连接,请告诉我!!
谢谢 卡维塔
最佳答案
import java.sql.Connection;
不是 jdbc 连接,因此您不需要任何连接转换
并且您的数据源连接变为
Connect con = ds.getConnection();
关于java - Glassfish 3.1.2 中的连接池遇到 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12471107/