afunms

My Software,My Dream—Forge a more perfect NMS product.

perfect DAO design

perfect DAO solution

------BaseDao------
public abstract class BaseDao
{  
   private static final int maxRow = 1000;
   protected Connection conn;
   protected String table;
   protected Class<? extends DtoInterface> dtoClass;
   protected JspPage jspPage;
   protected boolean insideConnection;
           
   public BaseDao(Connection conn)
   { 
    init();
    if(conn==null)
    {
     this.conn = ConnectionManager.getConnection();
     insideConnection = true;        
    }
    else
    {
        this.conn = conn;   
        insideConnection = false;
    }
   }

   public BaseDao()
   { 
    init();
    this.conn = ConnectionManager.getConnection();
    insideConnection = true;   
   }

   public void close(Statement stmt,ResultSet rs)
   {
    try
       {
          if(rs!= null)
             rs.close();
          if(stmt!=null)
             stmt.close();
          /**
           * if the connection is passed from outside
           * do not close it.
           */
          if(insideConnection)
          ConnectionManager.close(conn);
       }
       catch(SQLException se)
       {   
       }
   }

   protected abstract void init();
}

------sub dao class example------
public class ProducerDao extends BaseDao
{
 public ProducerDao(Connection conn)
 {
  super(conn);
 } 
 
 protected void init()
    {
     super.dtoClass = ProducerDto.class;
     super.table = "nms_producer";
    } 

------client code-----
For the first scenario

   ProducerDao dao = new ProducerDao(null);
or ProducerDao dao = (ProducerDao)BeanFactory.newDao("producer");
   dao.method();

For the second scenario
   Connection conn = ConnectionManager.createConnection();
   ProducerDao dao1 = new ProducerDao(conn);
   AnOtherDao dao2 = new AnOtherDao(conn);
   dao1.method1();
   dao2.method2();
   dao2.method3();
   ConnectionManager.close(conn);   

or Connection conn = ConnectionManager.createConnection();
   ProducerDao dao = (ProducerDao)BeanFactory.newDao("producer",conn);
   AnOtherDao dao = (AnOtherDao)BeanFactory.newDao("another",conn);
   dao1.method1();
   dao2.method2();
   dao2.method3();
   ConnectionManager.close(conn);   

posted on 2007-05-11 10:35 afunms 阅读(137) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

My Links

News

留言簿(18)

随笔档案

相册

搜索

最新评论

阅读排行榜