sorry for the long post. I will try to be as clear as possible.
I'm creating an app for my Software Engineering class and I am in front of this problem:
As suggested by one of our teachers, I should assign the responsibility of managing database resources to DAOs. I created an abstract DAO class which creates the connection to my database (it's a PostgreSQL database) to manage every connection in a single class, which opens the stream and closes it after the result of a query is consumed through an abstract method that will be implemented by many concrete DAO singleton classes. At the end of the post, there is an example of what I coded.
Everything seems fine to me because thanks to the inheritance I can connect several and different DAOs to the database, that is my case. The true point now is that I can't figure out how can I process the data inside the ResultSet, without taking care of the query that was made or what method of one of the concrete classes asked for connection.
P.S.: I tried to look for some patterns/solutions but I didn't find anything that fit my case. P.P.S.: I know that I should use DataSource instead of DriverManager, but this is what was taught in class.
The abstract class Example:
public abstract class AbstractDAO {
private static final String URL = "my_url";
private static final String USR = "my_usr";
private static final String PWD = "my_pwd";
private final Logger logger = Logger.getLogger(getClass().getName());
protected void connect(String query){
try(Connection con = DriverManager.getConnection(URL, USR, PWD);
PreparedStatement pst = con.prepareStatement(query)){
ResultSet rs = pst.executeQuery();
processResult(rs);
}catch (SQLException e){
logger.log(Level.SEVERE, e.getMessage());
}
}
// abstract method to process atomically the result in each DAO.
protected abstract void processResult(ResultSet rs) throws SQLException;
}
The concrete class Example:
public class ConcreteDAO extends AbstractDAO {
private static ConcreteDAO instance = null;
private ConcreteDAO() {
super();
}
private static synchronized ConcreteDAO getInstance() {
if (ConcreteDAO.instance == null) {
ConcreteDAO.instance = new ConcreteDAO();
}
return ConcreteDAO.instance;
}
@Override
protected void processResult(ResultSet rs) throws SQLException {
int numCols = rs.getMetaData().getColumnCount();
while (rs.next()) {
for (int i = 1; i <= numCols; i++) {
System.out.println("\t" + rs.getString(i));
}
System.out.println("");
}
}
public static void main(String[] args) {
String query = "select name, surname from test";
getInstance().connect(query);
}
}
Aucun commentaire:
Enregistrer un commentaire