jdk1.5的推出为我们带来了枚举、泛型、foreach循环、同步工具包等等好东西。其中,泛型的使用为我们的代码开发提供了很大的简便,简化了我们的代码。

1、设计思路

1)GenericDao泛型类提供所有的增删改查功能;

2)所有的dao在继承GenericDao泛型类拥有自身的增删改查功能,不需再写其他代码。

2、实现GenericDao,基类

public abstract class GenericDao<T, PK extends Serializable> {

protected final Logger logger = LoggerFactory.getLogger(getClass());

public static final String POSTFIX_SELECTBYID = ".selectById";
public static final String POSTFIX_SELECTBYIDS = ".selectByIds";
public static final String POSTFIX_SELECTBYMAP = ".selectByMap";
public static final String POSTFIX_SELECTIDSLIKEBYMAP = ".selectIdsLikeByMap";
public static final String POSTFIX_PKSELECTMAP = ".pkSelectByMap";
public static final String POSTFIX_COUNT = ".count";
public static final String POSTFIX_COUNTLIKEBYMAP = ".countLikeByMap";
public static final String POSTFIX_INSERT = ".insert";
public static final String POSTFIX_DELETEBYID = ".deleteById";
public static final String POSTFIX_DELETEBYIDS = ".deleteByIds";
public static final String POSTFIX_DELETEBYIDSMAP = ".deleteByIdsMap";
public static final String POSTFIX_DELETEBYMAP = ".deleteByMap";
public static final String POSTFIX_UPDATE = ".update";
public static final String POSTFIX_UPDATEBYMAP = ".updateByMap";
public static final String POSTFIX_UPDATEBYIDSMAP = ".updateByIdsMap";

protected Class<T> clazz;

protected String clazzName;

protected T t;

// 定义主从数据库服务器,主数据库负责(Write op),从数据库负责(read op)
@Autowired
protected SqlMapClientTemplate masterSqlMapClientTemplate;

@Autowired
protected SqlMapClientTemplate slaveSqlMapClientTemplate;

public GenericDao() {
      // 通过范型反射,取得在子类中定义的class.
      clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
      clazzName = clazz.getSimpleName();
}

public Integer count(String propertyName, Object propertyValue) {
      return count(new String[]{propertyName},new Object[]{propertyValue});
}

public Integer count(String[] propertyNames, Object[] propertyValues) {

Map<String, Object> map = new HashMap<String, Object>();
     for (int i = 0; i < propertyNames.length; i++) {
         map.put(propertyNames[i], propertyValues[i]);
     }
    return (Integer) slaveSqlMapClientTemplate.queryForObject(clazz.getName() + POSTFIX_COUNT, map);
}

@Override
public Integer countLikeByMap(String[] propertyNames, Object[] propertyValues) {
         Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < propertyNames.length; i++) {
             map.put(propertyNames[i], propertyValues[i]);
        }
        return (Integer) slaveSqlMapClientTemplate.queryForObject(clazz.getName() + POSTFIX_COUNTLIKEBYMAP, map);
}

/** 根据自定义SqlMap中的条件语句查询出记录数量 */
public Integer countByStatementPostfix(String statementPostfix,String[] properties, Object[] propertyValues){
      Map<String, Object> map = new HashMap<String, Object>();
      for (int i = 0; i < properties.length; i++) {
          map.put(properties[i], propertyValues[i]);
      }
      return (Integer) slaveSqlMapClientTemplate.queryForObject(clazz.getName() + statementPostfix, map);
}
/**
* 通过id得到实体对象
*/
public T findById(PK id) {
       return (T) slaveSqlMapClientTemplate.queryForObject(clazz.getName() + POSTFIX_SELECTBYID, id);

}

/**
* 根据ids获取实体列表
*
* @param ids
* @return
*/
public List<T> findByIds(List<PK> ids) {
       return (List<T>) slaveSqlMapClientTemplate.queryForList(clazz.getName() + POSTFIX_SELECTBYIDS, ids);
}

/**
* 直接从数据库查询出ids列表(包括符合条件的所有id)
*
* @param properties
* 查询条件字段名
* @param propertyValues
* 字段取值
* @return
*/
public List<PK> findIdsBy(String[] properties, Object[] propertyValues, String orderBy, String order) {
        Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < properties.length; i++) {
            map.put(properties[i], propertyValues[i]);
        }
        if (orderBy != null) {
            map.put("orderBy", orderBy);
            map.put("order", order);
         }
        return (List<PK>) slaveSqlMapClientTemplate.queryForList(clazz.getName() + POSTFIX_PKSELECTMAP, map);
}

/**
* 根据条件查询结果
*
* @param properties
* 查询条件名
* @param propertyValues
* 查询条件值
* @return
*/
public List<T> findByMap(String[] properties, Object[] propertyValues, String orderBy, String order) {
         return (List<T>) slaveSqlMapClientTemplate.queryForList(clazz.getName() + POSTFIX_SELECTBYMAP, map);
}

/**
* 根据条件查询结果的id列表
*
* @param properties
* 查询条件名
* @param propertyValues
* 查询条件值
* @return
*/
public List<PK> findIdsByMap(String[] properties, Object[] propertyValues, String orderBy, String order) {
         Map<String, Object> map = new HashMap<String, Object>();
         for (int i = 0; i < properties.length; i++) {
                map.put(properties[i], propertyValues[i]);
         }
         if (orderBy != null) {
              map.put("orderBy", orderBy);
              map.put("order", order);
          }
           return (List<PK>) slaveSqlMapClientTemplate.queryForList(clazz.getName() + POSTFIX_PKSELECTMAP, map);
}

/**
* 分页查询(未处理缓存)
*
* @param properties
* 查询条件字段名
* @param propertyValues
* 字段取值
* @return
*/
public List<T> pageQueryBy(String[] properties, Object[] propertyValues, String orderBy, String order, int pageSize, int pageNo) {
        Map<String, Object> map = new HashMap<String, Object>();
         for (int i = 0; i < properties.length; i++) {
              map.put(properties[i], propertyValues[i]);
        }
         if (orderBy != null) {
                 map.put("orderBy", orderBy);
                 map.put("order", order);
         }
         map.put("limit", true);
         map.put("start", (pageNo - 1) * pageSize );// limit 操作
         map.put("end", pageSize);
         return (List<T>) slaveSqlMapClientTemplate.queryForList(clazz.getName() + POSTFIX_SELECTBYMAP, map);
}

/**
* 从数据库分页查询出ids列表的前200个id
*
* @param properties
* 查询条件字段名
* @param propertyValues
* 字段取值
* @return
*/
protected List<PK> pageQueryIdsBy(String[] properties, Object[] propertyValues, String orderBy, String order) {
       Map<String, Object> map = new HashMap<String, Object>();
       for (int i = 0; i < properties.length; i++) {
                 map.put(properties[i], propertyValues[i]);
        }
        if (orderBy != null) {
            map.put("orderBy", orderBy);
            map.put("order", order);
        }
        map.put("limit", true);
         map.put("start", 0);// 操作
         map.put("end", Config.getInstance().getPageCacheSize());
         return (List<PK>) slaveSqlMapClientTemplate.queryForList(clazz.getName() + POSTFIX_PKSELECTMAP, map);

}

/**
* 分页查询出id列表(处理缓存)
*
* @param properties
* 查询条件字段名
* @param propertyValues
* 字段取值
* @return
*/
public List<PK> pageQueryIdsByMap(String[] properties, Object[] propertyValues, String orderBy, String order, int pageSize, int pageNo) {
        Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < properties.length; i++) {
              map.put(properties[i], propertyValues[i]);
        }
         if (orderBy != null) {
             map.put("orderBy", orderBy);
             map.put("order", order);
         }
         map.put("limit", true);
         map.put("start", (pageNo - 1) * pageSize );// limit 操作
         map.put("end", pageSize);
         return (List<PK>) slaveSqlMapClientTemplate.queryForList(clazz.getName() + POSTFIX_PKSELECTMAP, map);
}

/** like分页查询(不走列表缓存) */
public List<T> pageLikeBy(String[] properties, Object[] propertyValues, String orderBy, String order, int pageSize, int pageNo){
      Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < properties.length; i++) {
             map.put(properties[i], propertyValues[i]);
        }
       if (orderBy != null) {
             map.put("orderBy", orderBy);
              map.put("order", order);
        }
        map.put("limit", true);
        map.put("start", (pageNo - 1) * pageSize );// limit 操作
        map.put("end", pageSize);
        List<PK> ids = (List<PK>) slaveSqlMapClientTemplate.queryForList(clazz.getName() + POSTFIX_SELECTIDSLIKEBYMAP, map);
        return findByIds(ids);
}

/**
* 新增对象
*/
public Serializable insert(T o) throws Exception {
       if (t instanceof QueryCachable) {
           // 清除受影响的缓存
           clearListCache(o);
        }
        return (Serializable) masterSqlMapClientTemplate.insert(clazz.getName() + POSTFIX_INSERT, o);
}

/**
* 更新对象
*/
public T update(T o) throws Exception {
      masterSqlMapClientTemplate.update(clazz.getName() + POSTFIX_UPDATE, o);
       return o;
}

/**
* 更新对象的部分属性
*/
public int update(PK id, String[] properties, Object[] propertyValues) throws Exception {
    // 更新数据库
     Map<String, Object> map = new HashMap<String, Object>();
     for (int i = 0; i < properties.length; i++) {
          map.put(properties[i], propertyValues[i]);
     }
      map.put("id", id);
       return masterSqlMapClientTemplate.update(clazz.getName() + POSTFIX_UPDATEBYMAP, map);
}

/**
* 根据ID列表更新对象的部分属性
*/
public int updateByIdsMap(List<PK> ids,String[] properties, Object[] propertyValues) throws Exception{
      // 更新数据库
       Map<String, Object> map = new HashMap<String, Object>();
       for (int i = 0; i < properties.length; i++) {
            map.put(properties[i], propertyValues[i]);
        }
        map.put("ids", ids);
        return masterSqlMapClientTemplate.update(clazz.getName() + POSTFIX_UPDATEBYIDSMAP, map);
}

/**
* 根据ID删除对象
*/
public void deleteById(PK id) throws Exception {
         masterSqlMapClientTemplate.delete(clazz.getName() + POSTFIX_DELETEBYID, id);
}

/**
* 根据ID删除对象
*/
public void deleteByIds(List<PK> ids) throws Exception {
          masterSqlMapClientTemplate.delete(clazz.getName() + POSTFIX_DELETEBYIDS, ids);
}

/** 根据ID及条件删除对象 */
public void deleteByIdsMap(List<PK> ids, String[] properties, Object[] propertyValues) throws Exception {
         Map<String, Object> map = new HashMap<String, Object>();
         for (int i = 0; i < properties.length; i++) {
                map.put(properties[i], propertyValues[i]);
         }
         map.put("ids", ids);
         masterSqlMapClientTemplate.delete(clazz.getName() + POSTFIX_DELETEBYIDSMAP, map);
}

/**
* 根据条件删除对象
*/
public int deleteByMap(String[] properties, Object[] propertyValues) throws Exception {

Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < properties.length; i++) {
             map.put(properties[i], propertyValues[i]);
        }
        return masterSqlMapClientTemplate.delete(clazz.getName() + POSTFIX_DELETEBYMAP, map);
}

/**
* 根据自定义SqlMap中的条件语句查询出列表(注意:不处理缓存)
*/
public List<T> findByStatementPostfix(String statementPostfix, String[] properties, Object[] propertyValues, String orderBy, String order) {
      Map<String, Object> map = new HashMap<String, Object>();
      for (int i = 0; i < properties.length; i++) {
           map.put(properties[i], propertyValues[i]);
       }
       if (orderBy != null) {
            map.put("orderBy", orderBy);
            map.put("order", order);
       }
         return slaveSqlMapClientTemplate.queryForList(clazz.getName() + statementPostfix, map);
}

/**
* 根据自定义SqlMap中的条件语句查询出列表(注意:不处理缓存)
*/
public List<T> pageQueryByStatementPostfix(String statementPostfix, String[] properties, Object[] propertyValues, String orderBy, String order,int pageSize,int pageNo) {
       Map<String, Object> map = new HashMap<String, Object>();
       for (int i = 0; i < properties.length; i++) {
               map.put(properties[i], propertyValues[i]);
         }
        if (orderBy != null) {
            map.put("orderBy", orderBy);
            map.put("order", order);
         }
         map.put("limit", true);
         map.put("start", (pageNo - 1) * pageSize );// limit 操作
         map.put("end", pageSize);
         List<PK> ids = (List<PK>) slaveSqlMapClientTemplate.queryForList(clazz.getName() + statementPostfix, map);
         return findByIds(ids);
}

/**
* 根据自定义SqlMap中的条件语句更新数据(注意:不处理缓存)
*/
public void updateByStatementPostfix(String statementPostfix, String[] properties, Object[] propertyValues) {
      Map<String, Object> map = new HashMap<String, Object>();
      for (int i = 0; i < properties.length; i++) {
              map.put(properties[i], propertyValues[i]);
        }
        masterSqlMapClientTemplate.update(clazz.getName() + statementPostfix, map);
}

/**
* 根据自定义SqlMap中的条件语句删除数据(注意:不处理缓存)
*/
public void deleteByStatementPostfix(String statementPostfix, String[] properties, Object[] propertyValues) {
     Map<String, Object> map = new HashMap<String, Object>();
     for (int i = 0; i < properties.length; i++) {
          map.put(properties[i], propertyValues[i]);
      }
      masterSqlMapClientTemplate.delete(clazz.getName() + statementPostfix, map);
}

/**
* 根据自定义SqlMap中的条件语句插入数据(注意:不处理缓存)
*/
public void insertByStatementPostfix(String statementPostfix, String[] properties, Object[] propertyValues) {
        Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < properties.length; i++) {
               map.put(properties[i], propertyValues[i]);
        }
          masterSqlMapClientTemplate.insert(clazz.getName() + statementPostfix, map);
    }

}

3、所有其他Dao只需继承GenericDao,传个具体的类型,不需再写增删改查的方法

package com.teacherclub.business.album.dao;

import org.springframework.stereotype.Repository;

import com.teacherclub.business.album.entity.Album;
import com.teacherclub.core.mem.MemcacheUtil;
import com.teacherclub.core.orm.EntityCachable;
import com.teacherclub.core.orm.dao.impl.GenericDao;

@Repository
public class AlbumDao extends GenericDao<Album,Integer> {  //传参数Album类

}

此泛型的实现,关键在于:clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

这在项目中经常使用。

使用泛型类简化ibatis系统架构的更多相关文章

  1. Windows Internals学习笔记(二)系统架构

    参考资料: 1. <Windows Internals> 2. http://bestcbooks.com 3. Windows Drive Kit 4. Microsoft Window ...

  2. 【转】深入分析 iBATIS 框架之系统架构与映射原理

    深入分析 iBATIS 框架之系统架构与映射原理 iBATIS 通过 SQL Map 将 Java 对象映射成 SQL 语句和将结果集再转化成 Java 对象,与其他 ORM 框架相比,既解决了 Ja ...

  3. 论 业务系统 架构 的 简化 (一) 不需要 MQ

    MQ , 就是 消息队列(Message Queue), 不知从什么时候起, MQ 被用来 搭建 分布式 业务系统 架构, 一个重要作用 就是用来  “削峰”   . 我们 这里 就来 讨论 如何 设 ...

  4. 异构(兼容dubbo)SOA系统架构(.net)优化升级

    前面一片文章已经提到我司的异构(兼容dubbo)SOA系统架构,解决了不少技术痛点,也还算比较完善,也顺利推广开来. 但作为项目的开发者,自己产品的问题心里是清楚的,离自己满意还是有不小的距离. 在推 ...

  5. Android系统架构说明介绍

    Android系统架构说明介绍 Android系统架构和一些普遍的操作系统差不多,都是采用了分层的架构,从他们之间的架构图看,Android系统架构分为四个层,从高层到低层分别是应用程序层.应用程序框 ...

  6. 系统架构师JD

    #################################################################################################### ...

  7. Android的系统架构

    转自Android的系统架构 从上图中可以看出,Android系统架构为四层结构,从上层到下层分别是应用程序层.应用程序框架层.系统运行库层以及Linux内核层,分别介绍如下:     1)应用程序层 ...

  8. Cola:一个分布式爬虫框架 - 系统架构 - Python4cn(news, jobs)

    Cola:一个分布式爬虫框架 - 系统架构 - Python4cn(news, jobs) Cola:一个分布式爬虫框架 发布时间:2013-06-17 14:58:27, 关注:+2034, 赞美: ...

  9. 大数据高并发系统架构实战方案(LVS负载均衡、Nginx、共享存储、海量数据、队列缓存)

    课程简介: 随着互联网的发展,高并发.大数据量的网站要求越来越高.而这些高要求都是基础的技术和细节组合而成的.本课程就从实际案例出发给大家原景重现高并发架构常用技术点及详细演练. 通过该课程的学习,普 ...

随机推荐

  1. RESTful API设计基本原则

    REST四个基本原则:1.使用HTTP动词:GET POST PUT DELETE:2.无状态连接,服务器端不应保存过多上下文状态,即每个请求都是独立的:3.为每个资源设置URI:4.通过XML JS ...

  2. AOSP 源码下载

    网上关于这块大部分教程都是无效的,因为墙的缘故,无法使用官方提供的下载链接,我这里使用了清华大学的镜像,是能够顺利将 AOSP 下载下来.如果你还没有安装 Ubuntu,请看<VirtualBo ...

  3. Linux 查看CPU、Memory等资源占用情况

    linux下获取占用CPU资源最多的10个进程,可以使用如下命令组合: ps aux|head -1;ps aux|grep -v PID|sort -rn -k +3|head linux下获取占用 ...

  4. Apache common-io AutoCloseInputStream 分析

    Apache common-io 包是常用的工具包,他提供了对IO操作的一些封装.首先看一下input包下的 AutoCloseInputStream 类 1: * This class is typ ...

  5. win2008 配置TLS1.2

    配置TLS1.2 提供两种方法, 选择其中一种就行了 1.手动设置 找到HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProv ...

  6. JavaScript 面向对象编程(三):非构造函数对象的继承

    JavaScript 面向对象编程(三):非构造函数对象的继承 一.什么是"非构造函数"的继承? 比如,现在有一个对象,叫做"中国人". var Chinese ...

  7. 五环之歌之PHP分页

    根据以往的经验,对于很多初学者,分页功能实现起来还是有一定的困难的,为了帮大家解决这样的问题:特此献上五环之歌.从此分页功能便是如小岳岳唱歌一样简练,漂亮,精干.哈哈,不闲扯了.正式进入千锋PHP五环 ...

  8. 笨办法学Python(二十四)

    习题 24: 更多练习 你离这本书第一部分的结尾已经不远了,你应该已经具备了足够的 Python 基础知识,可以继续学习一些编程的原理了,但你应该做更多的练习.这个练习的内容比较长,它的目的是锻炼你的 ...

  9. 基于LBS的多人聊天

  10. BFS变换素数,POJ(3126)

    题目链接:http://poj.org/problem?id=3126 解题报告: #include <iostream> #include <queue> #include ...