I am using DAO pattern. In my case the DAO does not open or close connection; instead connection is passed to it through constructor; it uses that connection to perform its job. Can connection passing through constructor to DAO layer be unsafe in any case? If yes please tell me how.
This is how I am using it:
This is the parent of all DAO implementations:
public abstract class SuperDAO {
private Connection connection;
public SuperDAO(Connection connection) { this.connection = connection; }
public Connection getConnection() { return this.connection; }
}
This is the User business object:
public class User {
private String userId;
private String password;
public String getUserId() { return this.userId; }
public void setUserId(String userId) { this.userId = userId; }
public String getPassword() { return this.password; }
public void setPassword(String password) { this.password = password; }
}
This is the DAO of User business object:
public interface UserDAO {
User getUser(String userId, String password);
}
This is the SQL Server implementation of DAO of User business object:
public class SQLServerUserDAO extends SuperDAO implements UserDAO {
public SQLServerUserDAO(Connection connection) { super(connection); }
public User getUser(String userId, String password) {
// perform task; use getConnection() for connection; dont close connection
}
}
This is the DAO Factory:
public abstract class DAOFactory {
public static final int SQL_SERVER = 1;
protected Connection connection;
public static DAOFactory getDAOFactory(int factoryType, Connection connection) {
DAOFactory daoFactory = null;
switch (factoryType) {
case SQL_SERVER:
daoFactory = new SQLServerDAOFactory();
daoFactory.connection = connection;
break;
}
return daoFactory;
}
public abstract UserDAO getUserDAO();
}
This is the SQL Server implementation of DAO Factory:
public class SQLServerDAOFactory extends DAOFactory {
public UserDAO getUserDAO() {
UserDAO userDAO = new SQLServerUserDAO(connection);
return userDAO;
}
}
And this is how I use it:
Connection connection = null;
try {
connection = ... // obtain a connection;
DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.SQL_SERVER, connection);
UserDAO userDAO = daoFactory.getUserDAO();
...
} finally {
connection.close();
}
In which cases this code will be broken? Please advise.
Thanks
Aucun commentaire:
Enregistrer un commentaire