I am working on a web application. I am using Struts for the
presentation layer. Also I am using DAO pattern for Database layer.
My doubt is about creating instance of DAO's. I am created a DAO
Factory which can create instances of DAO's. Whether I can go for
caching of DAO or Do I have to create a new DAO for everytime? Would
caching done as shown in the code below create Concurrency issues? or
please suggest the right way of going about it.
My Struts Action code is as follows:
public class WelcomeAction extends Action {
static Category log =
Category.getInstance(WelcomeAction.class.getName());
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws
Exception {
try{
UserDAO userDAO =
(UserDAO)DAOFactory.getInstance("com.share.dao.UserDAO");
ResultObj obj = (ResultObj)userDAO.getUserList();
List userList = (ArrayList)obj.getResults();
request.setAttribute("userList", userList);
}catch(Exception e){
e.printStackTrace();
return mapping.findForward("errorPage");
}
return mapping.findForward("success");
}
UserDAO code is as follows:
public abstract class UserDAO extends BaseDAO {
public Object getUserList() throws DBException{
Connection conn = null;
PreparedStatement stmt = null;
Object obj = null;
try{
conn = DBConnectionManager.getConnection();
stmt = conn.prepareStatement("Select * from USER_INFO where USER_ID
like ?");
stmt.setMaxRows(3);
stmt.setString(1, "%");
stmt.executeQuery();
obj = processGetUserList(stmt);
}catch(SQLException e){
throw new DBException(e.getMessage());
}finally{
DBConnectionManager.close(stmt);
DBConnectionManager.closeConnection(conn);
}
return obj;
}
And the DAO Factory is as follows:
package com.share.dao;
import java.util.HashMap;
public class DAOFactory
{
private static HashMap hash = new HashMap();
public DAOFactory()
{
}
public static BaseDAO getInstance(String daoName)
{
BaseDAO dao = null;
try
{
dao = (BaseDAO)hash.get(daoName);
if(dao == null)
dao = createNewInstance(daoName);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return dao;
}
private static synchronized BaseDAO createNewInstance(String
daoName)
{
BaseDAO dao = null;
try
{
dao = (BaseDAO)hash.get(daoName);
if(dao != null)
return dao;
Class daoClass = Class.forName(daoName + "Impl");
dao = (BaseDAO)daoClass.newInstance();
hash.put(daoName, dao);
}
catch(Exception ex)
{
ex.printStackTrace();
}
return dao;
}
}