无法将DataSource强制转换为com.mchange.v2.c3p0.PooledDataSource

时间:2012-12-23 22:36:50

标签: java jdbc

我正在尝试使用此代码创建一个context.xml:

    ComboPooledDataSource cpds = new ComboPooledDataSource();
    try {
        cpds.setDriverClass( "net.sourceforge.jtds.jdbc.Driver" ); //loads the jdbc driver     
        cpds.setJdbcUrl( "jdbc:jtds:sqlserver://10.38.28.77/MyDB" );   
        cpds.setUser("sa");                                  
        cpds.setPassword("password");   
        cpds.setMaxStatements( 180 );
    } catch (PropertyVetoException e) {
        e.printStackTrace();
    }      
    return cpds.getConnection();

我的意思是,将此硬编码设置转换为context.xml,如:

        <Resource name="jdbc/MyDBHrd" 
         driverClass="net.sourceforge.jtds.jdbc.Driver"
         maxPoolSize="100"
         minPoolSize="15"
         acquireIncrement="1"
         auth="Container"
         maxStatements="50"
         idleConnectionTestPeriod="3600"
         testConnectionOnCheckin="true"
         automaticTestTable="connection_test"
         maxIdleTime="21600"
         factory="org.apache.naming.factory.BeanFactory"
         type="com.mchange.v2.c3p0.ComboPooledDataSource"
         jdbcUrl="jdbc:jtds:sqlserver://192.168.114.130/MyDB"
         user="sa" password="password" />

但是这个context.xml在使用时:

    InitialContext cxt = new InitialContext();
    String jndiName = "java:/comp/env/jdbc/MyDBHrd";
    // Look up our data source
    ComboPooledDataSource dataSource = (ComboPooledDataSource) cxt.lookup(jndiName);

抛出:

ClassCastException: org.apache.tomcat.dbcp.dbcp.DataSource cannot be cast to com.mchange.v2.c3p0.PooledDataSource

1 个答案:

答案 0 :(得分:2)

你应该将数据源声明为普通的vanilla类型,而不是Combo的东西。您要求Tomcat创建一个数据源,它不会为您制作其中一个。如果需要将普通数据源包装在其中一个中,请在Java中执行此操作。