1.0          Other languages
 
 

4.3 Write your DAO class

 
 

In most case, you need to write your own DAO functions. Because the generated DAO functions are too simple, can't be used in complex case.

Many projects has the needs to query from more than one tables once. In these cases, we should write our own VO(value object) class. The new VO class can be a totally new Java bean class, or sub-class of generated database model class.

For example, table A has following columns:
XX
YY
ZZ
and table B has following columns:
SS
TT

We can write a new VO class for new query:

public class MyVO{
    String xx;
String ss;
public String getXx(){ return xx;
} public void setXx(String xx){ this.xx = xx;
} public String getSs(){ return ss;
} public void setSs(String ss){ this.ss = ss;
}
} ... String sql = "select A.XX,B.SS from A,B "; // sql += " where ...";
return this.queryBeanList(sql, null, MyVO.class);//each element is a MyVO object
...

The mapping is based on database column name and Java bean property name. No configuration file is need for this mapping.

For other update/delete operations, you can write your own DAO functions in ANSI SQL:

    public void decreaseInventory(String productItemId, long qty) {
        StringBuffer sql = new StringBuffer();
        sql.append("update inventory i set qty = qty - ?");
        sql.append(" where itemid = ?");
        List paraList = new LinkedList();
        paraList.add(new Long(qty));
        paraList.add(productItemId);
        int updateCount = this.update(sql.toString(), paraList.toArray());
        log.debug("udpate count:" + updateCount);

    }

Comparing to directly JDBC programming, the advantage is that we don't need to pay attention to resource closure. We don't use JDBC Connection/Statement/ResultSet here. And we don't need to write try catch here.