mardi 28 octobre 2014

DAO factory pattern createConnection from datasource


Vote count:

0




Referring to this article on DAO factory pattern, http://ift.tt/1j9o9jW


I have a CloudscapeDAOFactory , that has a public static Connection createConnection() method. I am using DriverManager.registerDriver() and DriverManager.getConnection() to create connection.



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


The individual DAO classes like say CloudscapeCustomerDAO [Example 9.4] calls CloudscapeDAOFactory.createConnection() to get a connection as required.



public class CloudscapeCustomerDAO implements
CustomerDAO {

public CloudscapeCustomerDAO() {
// initialization
}

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


Question: Now I am implementing connection pooling, and my problem is retaining the 'static' keyword in the createConnection() of the CloudscapeDAOFactory.


CloudscapeDAOFactory.java



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.

}


Springconfig.xml



<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>


asked 54 secs ago







DAO factory pattern createConnection from datasource

Aucun commentaire:

Enregistrer un commentaire