IBATIS Dao操作模板类
这一次介绍一下 ibatis 模板基类设计 实现公共方法,减少开发工作量 代码更整洁清淅
EntityDAO 类代码如下:
/**
*(#)EntityDAO.java1.02008-6-7上午09:25:37
*
*/
package com.keyi.util.dao;importjava.io.Serializable;
import java.util.List;public interface EntityDAO<T> {
/**
*根据主键查找对象
*
*@paramid
*主键值
*@return对象实体
*/
T findByPrimarykey(Serializable id);/**
*新增对象到数据库
*
*@paramo
*对象实体
*/
void insert(T o);/**
*更新对象实体到数据库
*
*@paramo
*对象实体
*/
void update(T o);/**
*根据主键删除对象
*
*@paramid
*主键值
*/
void deleteByPrimarykey(Serializable id);/**
*更新对象信息
*
*@paramstatementId
*sql语句名称后缀
*@paramparameters
*sql参数
*/
void update(String statementId, Object parameters);/**
*sql查询单个对象
*
*@paramstatementId
*sql语句名称后缀
*@paramparameters
*sql参数
*@return查询结果
*/
T queryForObject(String statementId, Object parameters);/**
*sql查询列表
*
*@paramstatementId
*sql语句名称后缀
*@paramparameters
*sql参数
*@return查询结果
*/
List<T>queryForList(StringstatementId,Objectparameters);
}IbatisEntityDao 类内容如下:
/**
*(#)IbatisEntityDao.java1.02008-6-7上午09:24:32
*
*/
package com.keyi.util.dao;import java.io.Serializable;
importjava.util.List;
import java.util.Map;import org.apache.commons.lang.StringUtils;
import com.keyi.util.page.Page;
@SuppressWarnings("unchecked")
publicclassIbatisEntityDao<T>extendsIbatisGenericDaoimplements
EntityDAO<T> {/**
*DAO所管理的Entity类型.
*/
protected Class<T> entityClass;protected String primaryKeyName;
/**
*在构造函数中将泛型T.class赋给entityClass.
*/
@SuppressWarnings("unchecked")
publicIbatisEntityDao(){
entityClass=GenericsUtils.getSuperClassGenricType(getClass());
}/**
*根据ID获取对象.
*/
publicTfindByPrimarykey(Serializableid){
returnget(getEntityClass(),id);
}/**
*取得entityClass.<p/>JDK1.4不支持泛型的子类可以抛开Class<T>entityClass,重载此函数达到相同效果。
*/
protectedClass<T>getEntityClass(){
returnentityClass;
}public String getIdName(Class clazz) {
return"id";
}/**
*分页查询.
*/
publicPagepagedQuery(MapparameterObject,intstart,intlimit){
returnpagedQuery(getEntityClass(),parameterObject,start,limit);
}/**
*分页查询.
*/
publicPagepagedQuery(MapparameterObject,intstart,intlimit,
StringcountSqlId,StringpageQuerySqlId){
if(StringUtils.isNotBlank(pageQuerySqlId))
returnpagedQuery(getEntityClass(),parameterObject,start,limit,
countSqlId,pageQuerySqlId);
else{
returnpagedQuery(getEntityClass(),parameterObject,start,limit);
}
}/**
*根据ID移除对象.
*/
publicvoiddeleteByPrimarykey(Serializableid){
removeById(getEntityClass(),id);
}/**
*保存对象.为了实现IEntityDao我在内部使用了insert和upate2个方法.
*/
publicvoidinsert(To){
super._insert(o);
}public void setPrimaryKeyName(String primaryKeyName) {
this.primaryKeyName=primaryKeyName;
}public List<T> queryForList(String statementId, Object parameters) { return super.queryForList(getEntityClass(), statementId, parameters);
}
public T queryForObject(String statementId, Object parameters) {
returnsuper.queryForObject(getEntityClass(),statementId,parameters);
}public void update(String statementId, Object parameters) { super.update(getEntityClass(), statementId, parameters);
}
public void update(T o) {
super._update(o);
}
}IbatisGenericDao 类内容如下:
/**
*(#)IbatisGenericDao.java1.02008-6-7上午09:20:13
*
*/
package com.keyi.util.dao;import java.io.Serializable;
importjava.util.HashMap;
importjava.util.List;
import java.util.Map;import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;import org.springframework.util.Assert;
import com.keyi.util.page.Page;
@SuppressWarnings("unchecked")
public class IbatisGenericDao extends SqlMapClientDaoSupport {public static final String POSTFIX_INSERT = ".insert";
public static final String POSTFIX_UPDATE = ".update";
public static final String POSTFIX_DELETE = ".delete";
public static final String POSTFIX_DELETE_PRIAMARYKEY = ".deleteByPrimaryKey";
public static final String POSTFIX_SELECT = ".select";
public static final String POSTFIX_GETALL = ".getAll";
public static final String POSTFIX_SELECTMAP = ".selectByMap";
public static final String POSTFIX_SELECTSQL = ".selectBySql";
public static final String POSTFIX_COUNT = ".count";
public static final String POSTFIX_QUERY = ".query";
/**
*根据ID获取对象
*/
public <T> T get(Class<T> entityClass, Serializable id) {T o = (T) getSqlMapClientTemplate().queryForObject(
getStatementId(entityClass,IbatisGenericDao.POSTFIX_SELECT),
id);
returno;
}/**
*新增对象
*/
publicvoid_insert(Objecto){
getSqlMapClientTemplate().insert(
getStatementId(o.getClass(),IbatisGenericDao.POSTFIX_INSERT),
o);
}/**
*保存对象
*/
publicvoid_update(Objecto){
getSqlMapClientTemplate().update(
getStatementId(o.getClass(),IbatisGenericDao.POSTFIX_UPDATE),
o);
}/**
*根据ID删除对象
*/
public<T>voidremoveById(Class<T>entityClass,Serializableid){
getSqlMapClientTemplate().delete(
getStatementId(entityClass,
IbatisGenericDao.POSTFIX_DELETE_PRIAMARYKEY),id);
}/**
*分页查询函数,使用PaginatedList.
*
*@paramstart
*@paramlimit@return含17117717记录数和当前页数据的Page对象.
*/
publicPagepagedQuery(ClassentityClass,MapparameterObject,intstart,
int limit) {Assert.isTrue(start >= 0, "pageNo should start from 0");
// 计算总数
IntegertotalCount=(Integer)getSqlMapClientTemplate()
.queryForObject(
getStatementId(entityClass,
IbatisGenericDao.POSTFIX_COUNT),
parameterObject);// 如果没有数据则返回Empty Page Assert.notNull(totalCount, "totalCount Error");
if (totalCount.intValue() == 0) {
returnnewPage();
}List list;
inttotalPageCount=0;
int startIndex = 0;// 如果pageSize小于0,则返回所有数捄1177,等同于getAll if (limit > 0) {
// 计算页数
totalPageCount=(totalCount/limit);
totalPageCount += ((totalCount % limit) > 0) ? 1 : 0;// 计算skip数量
if(totalCount>start){
startIndex=start;
}else{
startIndex=(totalPageCount-1)*limit;
}if (parameterObject == null) parameterObject = new HashMap();
parameterObject.put("startIndex", startIndex); parameterObject.put("endIndex", limit);
list = getSqlMapClientTemplate()
.queryForList(
getStatementId(entityClass,
IbatisGenericDao.POSTFIX_QUERY),
parameterObject);} else {
list=getSqlMapClientTemplate()
.queryForList(
getStatementId(entityClass,
IbatisGenericDao.POSTFIX_QUERY),
parameterObject);
}
returnnewPage(startIndex,totalCount,limit,list);
}/**
*分页查询函数,使用PaginatedList.
*
*@paramstart
*@paramlimit@return含17117717记录数和当前页数据的Page对象.
*/
publicPagepagedQuery(ClassentityClass,MapparameterObject,intstart,
int limit, String countSqlId, String pageQuerySqlId) {Assert.isTrue(start >= 0, "pageNo should start from 0");
// 计算总数
IntegertotalCount=(Integer)getSqlMapClientTemplate()
.queryForObject(
getStatementId(entityClass,
countSqlId),
parameterObject);// 如果没有数据则返回Empty Page Assert.notNull(totalCount, "totalCount Error");
if (totalCount.intValue() == 0) {
returnnewPage();
}List list;
inttotalPageCount=0;
int startIndex = 0;// 如果pageSize小于0,则返回所有数捄1177,等同于getAll if (limit > 0) {
// 计算页数
totalPageCount=(totalCount/limit);
totalPageCount += ((totalCount % limit) > 0) ? 1 : 0;// 计算skip数量
if(totalCount>=start){
startIndex=start;
}else{
startIndex=(totalPageCount-1)*limit;
}if (parameterObject == null) parameterObject = new HashMap();
parameterObject.put("startIndex", startIndex); parameterObject.put("endIndex", limit);
list = getSqlMapClientTemplate()
.queryForList(
getStatementId(entityClass,
pageQuerySqlId),
parameterObject);} else {
list=getSqlMapClientTemplate()
.queryForList(
getStatementId(entityClass,
pageQuerySqlId),
parameterObject);
}
returnnewPage(startIndex,totalCount,limit,list);
}/**
*getstatementidinSQLMapfile
*
*@paramentityClass
*entityclass
*@paramsuffix
*suffix
*@returnstatementid
*/
privateStringgetStatementId(ClassentityClass,Stringsuffix){
StringclassName=entityClass.getName();
StringshortName=className.replace(entityClass.getPackage().getName()
+".","");
returnshortName+suffix;
}public <T> List<T> queryForList(Class<T> entityClass, String statementId,
Objectparameters){
returngetSqlMapClientTemplate().queryForList(
getStatementId(entityClass,statementId),parameters);
}public <T> T queryForObject(Class<T> entityClass, String statementId,
Objectparameters){
return(T)getSqlMapClientTemplate().queryForObject(
getStatementId(entityClass,statementId),parameters);
}public void update(Class entityClass, String statementId, Object parameters) {
getSqlMapClientTemplate().update(
getStatementId(entityClass,statementId),parameters);
}
}GenericsUtils 类内容如下:
/**
*(#)GenericsUtils.java1.02008-6-7上午09:26:43
*
*/
package com.keyi.util.dao;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;
import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;
@SuppressWarnings("unchecked")
publicclassGenericsUtils{
private static final Log log = LogFactory.getLog(GenericsUtils.class);private GenericsUtils() { }
publicstaticClassgetSuperClassGenricType(Classclazz){
returngetSuperClassGenricType(clazz,0);
}public static Class getSuperClassGenricType(Class clazz, int index) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
log.warn(clazz.getSimpleName()+"'ssuperclassnotParameterizedType");
returnObject.class;
}Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
log.warn("Index:"+index+",Sizeof"+clazz.getSimpleName()+"'sParameterizedType:"
+params.length);
returnObject.class;
}
if(!(params[index]instanceofClass)){
log.warn(clazz.getSimpleName()+"notsettheactualclassonsuperclassgenericparameter");
returnObject.class;
}
return(Class)params[index];
}}
具体应用如下:
public interface UserDAO extends EntityDAO<User>{}
public class IbatisUserDAO extends IbatisEntityDao<User> implements UserDAO {
}
public interface NewsDAO extends EntityDAO<News>{
}public class IbatisNewsDAO extends IbatisEntityDao<News> implements NewsDAO {
}
楼上的解释一下。为何不能用分页呢?
/**
*(#)Page.java1.02008-6-7上午09:21:03
*
*/importjava.io.Serializable;
importjava.util.ArrayList;
import java.util.Collection;/**
*分页对象.包含当前页数据及分页信息如总记录数.
*
*@author狂狼爪哇
*/@SuppressWarnings("serial")public class Page implements Serializable {
public static int DEFAULT_PAGE_SIZE = 10;
private int pageSize = Page.DEFAULT_PAGE_SIZE; // 每页的记录数
private int start; // 当前页第一条数据在List中的位置,从0开始
private Collection data; // 当前页中存放的记录,类型一般为List
private int totalCount; // 总记录数
/**
*构造方法,只构造空页.
*/
publicPage(){
this(0,0,Page.DEFAULT_PAGE_SIZE,newArrayList());
}/**
*默认构造方法.
*
*@paramstart
*本页数据在数据库中的起始位置
*@paramtotalSize
*数据库中总记录条数
*@parampageSize
*本页容量
*@paramdata
*本页包含的数据
*/
publicPage(intstart,inttotalSize,intpageSize,Collectiondata){
this.pageSize=pageSize;
this.start=start;
totalCount=totalSize;
this.data=data;
}/**
*取总记录数.
*/
publicintgetTotalCount(){
returntotalCount;
}/**
*取总页数.
*/
publicintgetTotalPageCount(){
if(totalCount%pageSize==0)
returntotalCount/pageSize;
else
returntotalCount/pageSize+1;
}/**
*取每页数据容量.
*/
publicintgetPageSize(){
returnpageSize;
}/**
*取当前页中的记录.
*/
publicCollectiongetResult(){
returndata;
}/**
*取该页当前页码,页码从1开始.
*/
publicintgetCurrentPageNo(){
returnstart/pageSize+1;
}/**
*该页是否有下一页.
*/
publicbooleanhasNextPage(){
returngetCurrentPageNo()<getTotalPageCount()-1;
}/**
*该页是否有上一页.
*/
publicbooleanhasPreviousPage(){
returngetCurrentPageNo()>1;
}/**
*获取任一页第一条数据在数据集的位置,每页条数使用默认值.
*
*@see#getStartOfPage(int,int)
*/
protectedstaticintgetStartOfPage(intpageNo){
returnPage.getStartOfPage(pageNo,Page.DEFAULT_PAGE_SIZE);
}/**
*获取任一页第一条数据在数据集的位置.
*
*@parampageNo
*从1开始的页号
*@parampageSize
*每页记录条数
*@return该页第一条数据
*/
publicstaticintgetStartOfPage(intpageNo,intpageSize){
return(pageNo-1)*pageSize;
}
publicintgetCurrentPage(){
returnthis.getCurrentPageNo();
}
publicintgetTotalPage(){
returnthis.getTotalPageCount();
}
publicintgetStart(){
returnthis.start;
}
}domain 类:
import java.util.Date;
importjava.util.HashMap;
import java.util.Map;import org.apache.commons.lang.StringEscapeUtils;import org.apache.commons.lang.StringUtils;
import com.czuan.util.user.IUser;
/**
*功能:用户信息
*
*@author狂狼爪哇
*@version1.0
*@JDK5
*/
public class User implements IUser {private Long id;
/*
*用户名
*/
private String loginName;/*
*密码
*/
private String passWord;/*
*问题
*/
private String question;/*
*答案
*/
private String result;/*
*邮箱
*/
private String email;/*
*电话号码
*/
private String phone;/*
*手机号码
*/
private String tel;/*
*祥细地扯
*/
private String address;/**
*角色
*/
private Long role;/*
*传真
*/
private String fax;/*
*qq/MSN
*/
private String qqMsn;/*
*真实姓名
*/
private String name;/*
*身份证号码
*/
private String card;/*
*邮证号码
*/
privateStringpostalcode;
/**
*注册时间
*/
private Date registerDate;/*
*备注
*/
private String bak;public String getAddress() {
returnaddress;
}public void setAddress(String address) {
this.address=address;
}public String getBak() {
returnbak;
}public void setBak(String bak) {
this.bak=bak;
}public String getCard() {
returncard;
}public void setCard(String card) {
this.card=card;
}public String getEmail() {
returnemail;
}public void setEmail(String email) {
this.email=email;
}public String getFax() {
returnfax;
}public void setFax(String fax) {
this.fax=fax;
}public Long getId() {
returnid;
}public void setId(Long id) {
this.id=id;
}public String getLoginName() {
returnloginName;
}public void setLoginName(String loginName) {
this.loginName=loginName;
}public String getName() {
returnname;
}public void setName(String name) {
this.name=name;
}public String getPassWord() {
returnpassWord;
}public void setPassWord(String passWord) {
this.passWord=passWord;
}public String getPhone() {
returnphone;
}public void setPhone(String phone) {
this.phone=phone;
}public String getPostalcode() {
returnpostalcode;
}public void setPostalcode(String postalcode) {
this.postalcode=postalcode;
}public String getQqMsn() {
returnqqMsn;
}public void setQqMsn(String qqMsn) {
this.qqMsn=qqMsn;
}public String getQuestion() {
returnquestion;
}public void setQuestion(String question) {
this.question=question;
}public String getResult() {
returnresult;
}public void setResult(String result) {
this.result=result;
}public Long getRole() {
returnrole;
}public void setRole(Long role) {
this.role=role;
}public String getTel() {
returntel;
}public void setTel(String tel) {
this.tel=tel;
}@SuppressWarnings("unchecked")
publicMaptransfer2Map(){
Mapparameters=newHashMap();
if(StringUtils.isNotBlank(this.getLoginName()))
parameters.put("loginName","%"+StringEscapeUtils.escapeSql(this.getLoginName().trim())+"%");
if(StringUtils.isNotBlank(this.getPassWord()))
parameters.put("passWord","%"+StringEscapeUtils.escapeSql(this.getPassWord().trim())+"%");
if(StringUtils.isNotBlank(this.getQuestion()))
parameters.put("question","%"+StringEscapeUtils.escapeSql(this.getQuestion().trim())+"%");
if(StringUtils.isNotBlank(this.getResult()))
parameters.put("result","%"+StringEscapeUtils.escapeSql(this.getResult().trim())+"%");
if(StringUtils.isNotBlank(this.getEmail()))
parameters.put("email","%"+StringEscapeUtils.escapeSql(this.getEmail().trim())+"%");
if(StringUtils.isNotBlank(this.getPhone()))
parameters.put("phone","%"+StringEscapeUtils.escapeSql(this.getPhone().trim())+"%");
if(StringUtils.isNotBlank(this.getTel()))
parameters.put("tel","%"+StringEscapeUtils.escapeSql(this.getTel().trim())+"%");
if(StringUtils.isNotBlank(this.getFax()))
parameters.put("fax","%"+StringEscapeUtils.escapeSql(this.getFax().trim())+"%");
if(StringUtils.isNotBlank(this.getQqMsn()))
parameters.put("qqMsn","%"+StringEscapeUtils.escapeSql(this.getQqMsn().trim())+"%");
if(StringUtils.isNotBlank(this.getName()))
parameters.put("name","%"+StringEscapeUtils.escapeSql(this.getName().trim())+"%");
if(StringUtils.isNotBlank(this.getCard()))
parameters.put("card","%"+StringEscapeUtils.escapeSql(this.getCard().trim())+"%");
if(StringUtils.isNotBlank(this.getPostalcode()))
parameters.put("postalcode","%"+StringEscapeUtils.escapeSql(this.getPostalcode()).trim()+"%");
parameters.put("role",this.getRole());
returnparameters;
}public Date getRegisterDate() {
returnregisterDate;
}public void setRegisterDate(Date registerDate) {
this.registerDate=registerDate;
}
}