我们在使用Spring的JdbcTemplate 写DAO时,通常可以继承JdbcDaoSupport或直接通过setter方法注入JdbcTemplate。此外spring中还提供了JdbcTemplate 的简化版SimpleJdbcTemplate以及对应的SimpleJdbcDaoSupport。
SimpleJdbcTemplate提供了对范型的支持,在查询操作时能以更优雅的方式实现,JdbcTemplate则提供了较为丰富的更新操作。
SimpleJdbcDaoSupport可以分别提供JdbcTemplate和SimpleJdbcTemplate,我们可以通过直接或间接的继承SimpleJdbcDaoSupport来获取更大的灵活性。
package cn.slsoft.beans.basicinfo;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
public class Subject {
private int subid;
private String subName;
private int subtypeid;
private String subtypeName;
private String dcflag;
private String hscash;
private String detailflag;
private int attflag;
private int assistflag;
private String fullName;
private int pid;
private String pname;
...省略getter,setter...
public String toString(){
return ReflectionToStringBuilder.toString(this);
}
}
package cn.slsoft.dao.base;
import org.apache.log4j.Logger;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
public class BaseDAO extends SimpleJdbcDaoSupport {
protected Logger log = Logger.getLogger(this.getClass());
}
package cn.slsoft.dao.basicinfo;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import cn.slsoft.beans.basicinfo.Subject;
import cn.slsoft.dao.base.BaseDAO;
public class SubjectDAO extends BaseDAO{
public String getSubNameByID(int subid){
String sql = "select subname from s_shop where subid=?";
log.debug(sql);
return getSimpleJdbcTemplate().queryForObject(sql, String.class, subid);
}
public List<Subject> getSubjects(){
String sql = "select * from s_subject";
log.debug(sql);
return getSimpleJdbcTemplate()
.query(sql, new SubjectParameterizedRowMapper(), shopid,accid,value);
}
public int deleteSubjectById(int subid){
String sql = "delete from s_subject where subid=" + subid;
log.debug(sql);
return getJdbcTemplate().update(sql);
}
}
class SubjectParameterizedRowMapper implements ParameterizedRowMapper<Subject>{
@Override
public Subject mapRow(ResultSet rs, int i) throws SQLException {
Subject subject = new Subject();
subject.setAssistflag(rs.getInt("assistflag"));
subject.setAttflag(rs.getInt("attflag"));
subject.setDcflag(rs.getString("dcflag"));
subject.setDetailflag(rs.getString("detailflag"));
subject.setFullName(rs.getString("fullname"));
subject.setHscash(rs.getString("hscash"));
subject.setPid(rs.getInt("parentid"));
subject.setPname(rs.getString("pname"));
subject.setSubid(rs.getInt("subid"));
subject.setSubName(rs.getString("subname"));
subject.setSubtypeid(rs.getInt("subtypeid"));
subject.setSubtypeName(rs.getString("subtypename"));
return subject;
}
}