来自数据源的DAO工厂模式createConnection

时间:2014-10-28 14:44:00

标签: java spring

参考这篇关于DAO工厂模式的文章, http://www.oracle.com/technetwork/java/dataaccessobject-138824.html

我有一个CloudscapeDAOFactory,它有一个public static Connection createConnection()方法。 我正在使用DriverManager.registerDriver()DriverManager.getConnection()来创建连接。

//DriverManager.registerDriver(new OracleDriver());
//conn = DriverManager.getConnection(CONNECTION_URL);

CloudscapeCustomerDAO [例9.4]这样的各个DAO类调用CloudscapeDAOFactory.createConnection()来获取所需的连接。

public class CloudscapeCustomerDAO implements 
    CustomerDAO {

  public CloudscapeCustomerDAO() {
    // initialization 
  }

  // The methods in the class can use
  // CloudscapeDAOFactory.createConnection() 
  // to get a connection as required

问题:现在我正在实施连接池,我的问题正在保留' static'中的关键字 createConnection()的{​​{1}}。

CloudscapeDAOFactory.java

CloudscapeDAOFactory

Springconfig.xml

private DataSource dataSource;
private static Connection conn = null;

public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}


public static Connection createConnection() throws SQLException {
  conn = dataSource.getConnection()// incorrect static reference// compile time error
  // If I remove 'static' then CloudscapeCustomerDAO need an instance of CloudscapeDAOFactory to call this method!
  // If I plan to retain the 'static' then I need to declare DataSource also as static, which I feel is incorrect.

}

更新:<bean id="springDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" > <property name="url" value="jdbc:oracle:thin:@localhost:1521:SPRING_UNNI" /> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="username" value="unni" /> <property name="password" value="unni" /> <property name="removeAbandoned" value="true" /> <property name="initialSize" value="20" /> <property name="maxActive" value="30" /> </bean> <bean id="cloudscapeDAOFactory" class="com.myapp.dao.CloudscapeDAOFactory"> <property name="dataSource" ref="springDataSource"/> </bean> 也可用于调用存储过程。参考:Spring JDBC Template for calling Stored Procedures 这个问题不是w.r.使用JDBCTemplate。它只是一个有效使用工厂的createConnection()的核心java问题

update2:与此主题无关​​,但发出了注释:

注意:尝试连接时遇到问题: 错误:JDBCTemplate

通过更改

修复
TNS:listener does not currently know of SID given in connect descriptor

 <property name="url" value="jdbc:oracle:thin:@localhost:1521:SPRING_UNNI" />

0 个答案:

没有答案
相关问题