这一次介绍一下 ibatis 模板基类设计 实现公共方法,减少开发工作量
代码更整洁清淅
EntityDAO 类代码如下:
/**
* (#)EntityDAO.java 1.0 2008-6-7 上午09:25:37
*
*/
package com.keyi.util.dao;
import java.io.Serializable;
import java.util.List;
public interface EntityDAO<T> {
/**
* 根据主键查找对象
*
* @param id
* 主键值
* @return 对象实体
*/
T findByPrimarykey(Serializable id);
/**
* 新增对象到数据库
*
* @param o
* 对象实体
*/
void insert(T o);
/**
* 更新对象实体到数据库
*
* @param o
* 对象实体
*/
void update(T o);
/**
* 根据主键删除对象
*
* @param id
* 主键值
*/
void deleteByPrimarykey(Serializable id);
/**
* 更新对象信息
*
* @param statementId
* sql语句名称后缀
* @param parameters
* sql参数
*/
void update(String statementId, Object parameters);
/**
* sql查询单个对象
*
* @param statementId
* sql语句名称后缀
* @param parameters
* sql参数
* @return 查询结果
*/
T queryForObject(String statementId, Object parameters);
/**
* sql查询列表
*
* @param statementId
* sql语句名称后缀
* @param parameters
* sql参数
* @return 查询结果
*/
List<T> queryForList(String statementId, Object parameters);
}
IbatisEntityDao 类内容如下:
/**
* (#)IbatisEntityDao.java 1.0 2008-6-7 上午09:24:32
*
*/
package com.keyi.util.dao;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.keyi.util.page.Page;
@SuppressWarnings("unchecked")
public class IbatisEntityDao<T> extends IbatisGenericDao implements
EntityDAO<T> {
/**
* DAO所管理的Entity类型.
*/
protected Class<T> entityClass;
protected String primaryKeyName;
/**
* 在构造函数中将泛型T.class赋给entityClass.
*/
@SuppressWarnings("unchecked")
public IbatisEntityDao() {
entityClass = GenericsUtils.getSuperClassGenricType(getClass());
}
/**
* 根据ID获取对象.
*/
public T findByPrimarykey(Serializable id) {
return get(getEntityClass(), id);
}
/**
* 取得entityClass. <p/> JDK1.4不支持泛型的子类可以抛开Class<T> entityClass,重载此函数达到相同效果。
*/
protected Class<T> getEntityClass() {
return entityClass;
}
public String getIdName(Class clazz) {
return "id";
}
/**
* 分页查询.
*/
public Page pagedQuery(Map parameterObject, int start, int limit) {
return pagedQuery(getEntityClass(), parameterObject, start, limit);
}
/**
* 分页查询.
*/
public Page pagedQuery(Map parameterObject, int start, int limit,
String countSqlId, String pageQuerySqlId) {
if (StringUtils.isNotBlank(pageQuerySqlId))
return pagedQuery(getEntityClass(), parameterObject, start, limit,
countSqlId, pageQuerySqlId);
else {
return pagedQuery(getEntityClass(), parameterObject, start, limit);
}
}
/**
* 根据ID移除对象.
*/
public void deleteByPrimarykey(Serializable id) {
removeById(getEntityClass(), id);
}
/**
* 保存对象. 为了实现IEntityDao 我在内部使用了insert和upate 2个方法.
*/
public void insert(T o) {
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) {
return super.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.java 1.0 2008-6-7 上午09:20:13
*
*/
package com.keyi.util.dao;
import java.io.Serializable;
import java.util.HashMap;
import java.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);
return o;
}
/**
* 新增对象
*/
public void _insert(Object o) {
getSqlMapClientTemplate().insert(
getStatementId(o.getClass(), IbatisGenericDao.POSTFIX_INSERT),
o);
}
/**
* 保存对象
*/
public void _update(Object o) {
getSqlMapClientTemplate().update(
getStatementId(o.getClass(), IbatisGenericDao.POSTFIX_UPDATE),
o);
}
/**
* 根据ID删除对象
*/
public <T> void removeById(Class<T> entityClass, Serializable id) {
getSqlMapClientTemplate().delete(
getStatementId(entityClass,
IbatisGenericDao.POSTFIX_DELETE_PRIAMARYKEY), id);
}
/**
* 分页查询函数,使用PaginatedList.
*
* @param start
*@param limit @return 含17117717记录数和当前页数据的Page对象.
*/
public Page pagedQuery(Class entityClass, Map parameterObject, int start,
int limit) {
Assert.isTrue(start >= 0, "pageNo should start from 0");
// 计算总数
Integer totalCount = (Integer) getSqlMapClientTemplate()
.queryForObject(
getStatementId(entityClass,
IbatisGenericDao.POSTFIX_COUNT),
parameterObject);
// 如果没有数据则返回Empty Page
Assert.notNull(totalCount, "totalCount Error");
if (totalCount.intValue() == 0) {
return new Page();
}
List list;
int totalPageCount = 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);
}
return new Page(startIndex, totalCount, limit, list);
}
/**
* 分页查询函数,使用PaginatedList.
*
* @param start
*@param limit @return 含17117717记录数和当前页数据的Page对象.
*/
public Page pagedQuery(Class entityClass, Map parameterObject, int start,
int limit, String countSqlId, String pageQuerySqlId) {
Assert.isTrue(start >= 0, "pageNo should start from 0");
// 计算总数
Integer totalCount = (Integer) getSqlMapClientTemplate()
.queryForObject(
getStatementId(entityClass,
countSqlId),
parameterObject);
// 如果没有数据则返回Empty Page
Assert.notNull(totalCount, "totalCount Error");
if (totalCount.intValue() == 0) {
return new Page();
}
List list;
int totalPageCount = 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);
}
return new Page(startIndex, totalCount, limit, list);
}
/**
* get statement id in SQL Map file
*
* @param entityClass
* entity class
* @param suffix
* suffix
* @return statement id
*/
private String getStatementId(Class entityClass, String suffix) {
String className = entityClass.getName();
String shortName = className.replace(entityClass.getPackage().getName()
+ ".", "");
return shortName + suffix;
}
public <T> List<T> queryForList(Class<T> entityClass, String statementId,
Object parameters) {
return getSqlMapClientTemplate().queryForList(
getStatementId(entityClass, statementId), parameters);
}
public <T> T queryForObject(Class<T> entityClass, String statementId,
Object parameters) {
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.java 1.0 2008-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")
public class GenericsUtils {
private static final Log log = LogFactory.getLog(GenericsUtils.class);
private GenericsUtils() {
}
public static Class getSuperClassGenricType(Class clazz) {
return getSuperClassGenricType(clazz, 0);
}
public static Class getSuperClassGenricType(Class clazz, int index) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
log.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
log.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
+ params.length);
return Object.class;
}
if (!(params[index] instanceof Class)) {
log.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
return Object.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.java 1.0 2008-6-7 上午09:21:03
*
*/
import java.io.Serializable;
import java.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; // 总记录数
/**
* 构造方法,只构造空页.
*/
public Page() {
this(0, 0, Page.DEFAULT_PAGE_SIZE, new ArrayList());
}
/**
* 默认构造方法.
*
* @param start
* 本页数据在数据库中的起始位置
* @param totalSize
* 数据库中总记录条数
* @param pageSize
* 本页容量
* @param data
* 本页包含的数据
*/
public Page(int start, int totalSize, int pageSize, Collection data) {
this.pageSize = pageSize;
this.start = start;
totalCount = totalSize;
this.data = data;
}
/**
* 取总记录数.
*/
public int getTotalCount() {
return totalCount;
}
/**
* 取总页数.
*/
public int getTotalPageCount() {
if (totalCount % pageSize == 0)
return totalCount / pageSize;
else
return totalCount / pageSize + 1;
}
/**
* 取每页数据容量.
*/
public int getPageSize() {
return pageSize;
}
/**
* 取当前页中的记录.
*/
public Collection getResult() {
return data;
}
/**
* 取该页当前页码,页码从1开始.
*/
public int getCurrentPageNo() {
return start / pageSize + 1;
}
/**
* 该页是否有下一页.
*/
public boolean hasNextPage() {
return getCurrentPageNo() < getTotalPageCount() - 1;
}
/**
* 该页是否有上一页.
*/
public boolean hasPreviousPage() {
return getCurrentPageNo() > 1;
}
/**
* 获取任一页第一条数据在数据集的位置,每页条数使用默认值.
*
* @see #getStartOfPage(int,int)
*/
protected static int getStartOfPage(int pageNo) {
return Page.getStartOfPage(pageNo, Page.DEFAULT_PAGE_SIZE);
}
/**
* 获取任一页第一条数据在数据集的位置.
*
* @param pageNo
* 从1开始的页号
* @param pageSize
* 每页记录条数
* @return 该页第一条数据
*/
public static int getStartOfPage(int pageNo, int pageSize) {
return (pageNo - 1) * pageSize;
}
public int getCurrentPage() {
return this.getCurrentPageNo();
}
public int getTotalPage() {
return this.getTotalPageCount();
}
public int getStart() {
return this.start;
}
}
domain 类:
import java.util.Date;
import java.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 狂狼爪哇
* @version 1.0
* @JDK 5
*/
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;
/*
* 邮证号码
*/
private String postalcode;
/**
* 注册时间
*/
private Date registerDate;
/*
* 备注
*/
private String bak;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getBak() {
return bak;
}
public void setBak(String bak) {
this.bak = bak;
}
public String getCard() {
return card;
}
public void setCard(String card) {
this.card = card;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPostalcode() {
return postalcode;
}
public void setPostalcode(String postalcode) {
this.postalcode = postalcode;
}
public String getQqMsn() {
return qqMsn;
}
public void setQqMsn(String qqMsn) {
this.qqMsn = qqMsn;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Long getRole() {
return role;
}
public void setRole(Long role) {
this.role = role;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
@SuppressWarnings("unchecked")
public Map transfer2Map(){
Map parameters = new HashMap();
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());
return parameters;
}
public Date getRegisterDate() {
return registerDate;
}
public void setRegisterDate(Date registerDate) {
this.registerDate = registerDate;
}
}