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