现在的位置: 首页 > 综合 > 正文

mybatis 基于泛型dao设计

2018年05月07日 ⁄ 综合 ⁄ 共 17654字 ⁄ 字号 评论关闭

1,用户分页的参数类

[java] view
plain
copy

  1. package hwt.Utils;  
  2.   
  3. import java.util.Map;  
  4.   
  5. public class PageEntity {  
  6.     private Integer page; //目前是第几页  
  7.     private Integer size; //每页大小  
  8.     private Map params; //传入的参数  
  9.     private String orderColumn;  
  10.     private String orderTurn = "ASC";  
  11.       
  12.     public String getOrderColumn() {  
  13.         return orderColumn;  
  14.     }  
  15.     public void setOrderColumn(String orderColumn) {  
  16.         this.orderColumn = orderColumn;  
  17.     }  
  18.     public String getOrderTurn() {  
  19.         return orderTurn;  
  20.     }  
  21.     public void setOrderTurn(String orderTurn) {  
  22.         this.orderTurn = orderTurn;  
  23.     }  
  24.     public Integer getPage() {  
  25.         return page;  
  26.     }  
  27.     public void setPage(Integer page) {  
  28.         this.page = page;  
  29.     }  
  30.     public Integer getSize() {  
  31.         return size;  
  32.     }  
  33.     public void setSize(Integer size) {  
  34.         this.size = size;  
  35.     }  
  36.     public Map getParams() {  
  37.         return params;  
  38.     }  
  39.     public void setParams(Map params) {  
  40.         this.params = params;  
  41.     }  
  42. }  


2,分页结果类

[java] view
plain
copy

  1. package hwt.Utils;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. /** 
  7.  * 分页结果 
  8.  * @author hwt 
  9.  * 
  10.  */  
  11. public class PagingResult<T> {  
  12.     //当前页  
  13.     private int currentPage;  
  14.     //总共记录条数  
  15.     private int totalSize;  
  16.     //结果集  
  17.     private List<T> resultList = new ArrayList<T>();  
  18.       
  19.       
  20.     public int getCurrentPage() {  
  21.         return currentPage;  
  22.     }  
  23.     public void setCurrentPage(int currentPage) {  
  24.         this.currentPage = currentPage;  
  25.     }  
  26.     public int getTotalSize() {  
  27.         return totalSize;  
  28.     }  
  29.     public void setTotalSize(int totalSize) {  
  30.         this.totalSize = totalSize;  
  31.     }  
  32.     public List<T> getResultList() {  
  33.         return resultList;  
  34.     }  
  35.     public void setResultList(List<T> resultList) {  
  36.         this.resultList = resultList;  
  37.     }  
  38. }  


3,BaseDAO接口

[java] view
plain
copy

  1. package hwt.DAO;  
  2.   
  3. import hwt.Utils.PageEntity;  
  4. import hwt.Utils.PagingResult;  
  5.   
  6. import java.io.Serializable;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9.   
  10.   
  11. /** 
  12.  * baseDAO 
  13.  * @author hwt 
  14.  * 
  15.  */  
  16. public interface BaseDAO<T,PK extends Serializable> {  
  17.       
  18.     /** 
  19.      * 新增实体 
  20.      * @param entity 
  21.      * @return 影响记录条数 
  22.      */  
  23.     public abstract int insert(T entity);  
  24.       
  25.     /**  
  26.      * 修改一个实体对象(UPDATE一条记录)  
  27.      * @param entity 实体对象  
  28.      * @return 修改的对象个数,正常情况=1  
  29.      */    
  30.     public abstract int update(T entity);    
  31.         
  32.     /**  
  33.      * 修改符合条件的记录  
  34.      * <p>此方法特别适合于一次性把多条记录的某些字段值设置为新值(定值)的情况,比如修改符合条件的记录的状态字段</p>  
  35.      * <p>此方法的另一个用途是把一条记录的个别字段的值修改为新值(定值),此时要把条件设置为该记录的主键</p>  
  36.      * @param param 用于产生SQL的参数值,包括WHERE条件、目标字段和新值等  
  37.      * @return 修改的记录个数,用于判断修改是否成功  
  38.      */    
  39.     public abstract int updateParam(Map param);    
  40.         
  41.     /**  
  42.      * 按主键删除记录  
  43.      * @param primaryKey 主键对象  
  44.      * @return 删除的对象个数,正常情况=1  
  45.      */    
  46.     public abstract int delete(PK primaryKey);    
  47.     
  48.     /**  
  49.      * 删除符合条件的记录  
  50.      * <p><strong>此方法一定要慎用,如果条件设置不当,可能会删除有用的记录!</strong></p>  
  51.      * @param param 用于产生SQL的参数值,包括WHERE条件(其他参数内容不起作用)  
  52.      * @return  
  53.      */    
  54.     public abstract int deleteParam(Map param);    
  55.         
  56.     /**  
  57.      * 清空表,比delete具有更高的效率,而且是从数据库中物理删除(delete是逻辑删除,被删除的记录依然占有空间)  
  58.      * <p><strong>此方法一定要慎用!</strong></p>  
  59.      * @return  
  60.      */    
  61.     public abstract int truncate();    
  62.         
  63.     /**  
  64.      * 查询整表总记录数  
  65.      * @return 整表总记录数  
  66.      */    
  67.     public abstract int count();    
  68.         
  69.     /**  
  70.      * 查询符合条件的记录数  
  71.      * @param param 查询条件参数,包括WHERE条件(其他参数内容不起作用)。此参数设置为null,则相当于count()  
  72.      * @return  
  73.      */    
  74.     public abstract int count(Object param);    
  75.     
  76.     /**  
  77.      * 按主键取记录  
  78.      * @param primaryKey 主键值  
  79.      * @return 记录实体对象,如果没有符合主键条件的记录,则返回null  
  80.      */    
  81.     public abstract T get(PK primaryKey);    
  82.     
  83.     /**  
  84.      * 取全部记录  
  85.      * @return 全部记录实体对象的List  
  86.      */    
  87.     public abstract List<T> select();    
  88.         
  89.     /**  
  90.      * 按条件查询记录  
  91.      * @param param 查询条件参数,包括WHERE条件、分页条件、排序条件  
  92.      * @return 符合条件记录的实体对象的List  
  93.      */    
  94.     public abstract List<T> selectParam(Map param);    
  95.         
  96.     /**  
  97.      * 按条件查询记录,并处理成分页结果  
  98.      * @param param 查询条件参数,包括WHERE条件、分页条件、排序条件  
  99.      * @return PaginationResult对象,包括(符合条件的)总记录数、页实体对象List等  
  100.      */    
  101.     public abstract PagingResult<T> selectPagination(PageEntity param);    
  102.         
  103.     /**  
  104.      * 批量插入  
  105.      * @param list  
  106.      */    
  107.     public abstract int insertBatch(final List<T> list);    
  108.         
  109.     /**  
  110.      * 批量修改  
  111.      * @param list  
  112.      */    
  113.     public abstract int updateBatch(final List<T> list);    
  114.         
  115.     /**  
  116.      * 批量删除  
  117.      * @param list  
  118.      */    
  119.     public abstract int deleteBatch(final List<PK> list);    
  120. }  


4,BaseDAO的实现类

[java] view
plain
copy

  1. package hwt.DAO;  
  2.   
  3. import hwt.Utils.PageEntity;  
  4. import hwt.Utils.PagingResult;  
  5.   
  6. import java.io.Serializable;  
  7. import java.text.SimpleDateFormat;  
  8. import java.util.Date;  
  9. import java.util.HashMap;  
  10. import java.util.List;  
  11. import java.util.Map;  
  12.   
  13. import javax.annotation.Resource;  
  14.   
  15. import org.apache.ibatis.mapping.BoundSql;  
  16. import org.apache.ibatis.mapping.MappedStatement;  
  17. import org.apache.ibatis.session.Configuration;  
  18. import org.apache.ibatis.session.RowBounds;  
  19. import org.mybatis.spring.SqlSessionTemplate;  
  20. import org.mybatis.spring.support.SqlSessionDaoSupport;  
  21.   
  22. /** 
  23.  * baseDAO的实现基类 
  24.  *  
  25.  * @author hwt 
  26.  *  
  27.  * @param <T> 
  28.  * @param <PK> 
  29.  */  
  30. public class BaseDaoImpl<T, PK extends Serializable> extends  
  31.         SqlSessionDaoSupport implements BaseDAO<T, PK> {  
  32.     // mapper.xml中的namespace  
  33.     private String namespace;  
  34.   
  35.     // sqlmap.xml定义文件中对应的sqlid  
  36.     public static final String SQLID_INSERT = "insert";  
  37.     public static final String SQLID_INSERT_BATCH = "insertBatch";  
  38.     public static final String SQLID_UPDATE = "update";  
  39.     public static final String SQLID_UPDATE_PARAM = "updateParam";  
  40.     public static final String SQLID_UPDATE_BATCH = "updateBatch";  
  41.     public static final String SQLID_DELETE = "delete";  
  42.     public static final String SQLID_DELETE_PARAM = "deleteParam";  
  43.     public static final String SQLID_DELETE_BATCH = "deleteBatch";  
  44.     public static final String SQLID_TRUNCATE = "truncate";  
  45.     public static final String SQLID_SELECT = "select";  
  46.     public static final String SQLID_SELECT_PK = "selectPk";  
  47.     public static final String SQLID_SELECT_PARAM = "selectParam";  
  48.     public static final String SQLID_SELECT_FK = "selectFk";  
  49.     public static final String SQLID_COUNT = "count";  
  50.     public static final String SQLID_COUNT_PARAM = "countParam";  
  51.   
  52.     @Resource(name = "sqlSessionTemplate")  
  53.     public void setSuperSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {  
  54.         super.setSqlSessionTemplate(sqlSessionTemplate);  
  55.     }  
  56.   
  57.     public String getNamespace() {  
  58.         return namespace;  
  59.     }  
  60.   
  61.     public void setNamespace(String namespace) {  
  62.         this.namespace = namespace;  
  63.     }  
  64.   
  65.     @Override  
  66.     public int insert(T entity) {  
  67.         int rows = 0;  
  68.         try {  
  69.             rows = getSqlSession().insert(namespace + "." + SQLID_INSERT,  
  70.                     entity);  
  71.         } catch (Exception e) {  
  72.             e.printStackTrace();  
  73.         }  
  74.         return rows;  
  75.     }  
  76.   
  77.     @Override  
  78.     public int update(T entity) {  
  79.         int rows = 0;  
  80.         try {  
  81.             rows = getSqlSession().update(namespace + "." + SQLID_UPDATE,  
  82.                     entity);  
  83.         } catch (Exception e) {  
  84.             e.printStackTrace();  
  85.         }  
  86.         return rows;  
  87.     }  
  88.   
  89.     @Override  
  90.     public int updateParam(Map param) {  
  91.         int rows = 0;  
  92.         try {  
  93.             rows = getSqlSession().update(namespace + "." + SQLID_UPDATE_PARAM,  
  94.                     param);  
  95.         } catch (Exception e) {  
  96.             e.printStackTrace();  
  97.         }  
  98.         return rows;  
  99.     }  
  100.   
  101.     @Override  
  102.     public int delete(PK primaryKey) {  
  103.         int rows = 0;  
  104.         try {  
  105.             rows = getSqlSession().delete(namespace + "." + SQLID_DELETE,  
  106.                     primaryKey);  
  107.         } catch (Exception e) {  
  108.             e.printStackTrace();  
  109.         }  
  110.         return rows;  
  111.     }  
  112.   
  113.     @Override  
  114.     public int deleteParam(Map param) {  
  115.         int rows = 0;  
  116.         try {  
  117.             rows = getSqlSession().delete(namespace + "." + SQLID_DELETE_PARAM,  
  118.                     param);  
  119.         } catch (Exception e) {  
  120.             e.printStackTrace();  
  121.         }  
  122.         return rows;  
  123.     }  
  124.   
  125.     @Override  
  126.     public int truncate() {  
  127.         int rows = 0;  
  128.         try {  
  129.             rows = getSqlSession().delete(namespace + "." + SQLID_TRUNCATE);  
  130.         } catch (Exception e) {  
  131.             e.printStackTrace();  
  132.         }  
  133.         return rows;  
  134.     }  
  135.   
  136.     @Override  
  137.     public int count() {  
  138.         int result = 0;  
  139.         try {  
  140.             result = getSqlSession().selectOne(namespace + "." + SQLID_COUNT);  
  141.         } catch (Exception e) {  
  142.             e.printStackTrace();  
  143.         }  
  144.         return result;  
  145.     }  
  146.   
  147.     @Override  
  148.     public int count(Object param) {  
  149.         int result = 0;  
  150.         try {  
  151.             result = getSqlSession().selectOne(namespace + "." + SQLID_COUNT_PARAM,param);  
  152.         } catch (Exception e) {  
  153.             e.printStackTrace();  
  154.         }  
  155.         return result;  
  156.     }  
  157.   
  158.     @Override  
  159.     public T get(PK primaryKey) {  
  160.         try {  
  161.             return getSqlSession().selectOne(namespace + "." + SQLID_SELECT_PK,primaryKey);  
  162.         } catch (Exception e) {  
  163.             e.printStackTrace();  
  164.             return null;  
  165.         }  
  166.     }  
  167.   
  168.     @Override  
  169.     public List<T> select() {  
  170.         try {  
  171.             return getSqlSession().selectList(namespace + "." + SQLID_SELECT);  
  172.         } catch (Exception e) {  
  173.             e.printStackTrace();  
  174.             return null;  
  175.         }  
  176.           
  177.     }  
  178.   
  179.     @Override  
  180.     public List<T> selectParam(Map param) {  
  181.         try {  
  182.             return getSqlSession().selectList(namespace + "." + SQLID_SELECT_PARAM,param);  
  183.         } catch (Exception e) {  
  184.             e.printStackTrace();  
  185.             return null;  
  186.         }  
  187.     }  
  188.   
  189.     @Override  
  190.     public PagingResult<T> selectPagination(PageEntity pageEntity) {  
  191.         try {  
  192.             int page = pageEntity.getPage() == null || "".equals(pageEntity.getPage()) ? 1 : pageEntity.getPage(); //默认为第一页  
  193.             int size = pageEntity.getSize() == null || "".equals(pageEntity.getSize()) ? 15 : pageEntity.getSize();; //默认每页15个  
  194.               
  195.             RowBounds rowBounds = new RowBounds((page-1)*size, size);  
  196.               
  197.             Map param = pageEntity.getParams();  
  198.             if (param != null) {  
  199.                 param.put("orderColumn", pageEntity.getOrderColumn());  
  200.                 param.put("orderTurn", pageEntity.getOrderTurn());  
  201.             }else {  
  202.                 param = new HashMap();  
  203.                 param.put("orderColumn", pageEntity.getOrderColumn());  
  204.                 param.put("orderTurn", pageEntity.getOrderTurn());  
  205.             }  
  206.               
  207.             List<T> resultList = getSqlSession().selectList(namespace + "." + SQLID_SELECT_PARAM,param,rowBounds);  
  208.             int totalSize = count(pageEntity.getParams());  
  209.               
  210.             PagingResult<T> pagingResult = new PagingResult<T>();  
  211.             pagingResult.setCurrentPage(page);  
  212.             pagingResult.setTotalSize(totalSize);  
  213.             pagingResult.setResultList(resultList);  
  214.             return pagingResult;  
  215.               
  216.         } catch (Exception e) {  
  217.             e.printStackTrace();  
  218.             return null;  
  219.         }  
  220.     }  
  221.   
  222.   
  223.     @Override  
  224.     public int insertBatch(List<T> list) {  
  225.         try {  
  226.             return getSqlSession().insert(namespace + "." + SQLID_INSERT_BATCH,list);  
  227.         } catch (Exception e) {  
  228.             e.printStackTrace();  
  229.             return 0;  
  230.         }  
  231.     }  
  232.    
  233.     @Override  
  234.     public int updateBatch(List<T> list) {  
  235.         int rows = 0;  
  236.         try {  
  237.             for (T t : list) {  
  238.                 rows = rows + getSqlSession().update(namespace + "." + SQLID_UPDATE, t);  
  239.             }  
  240.         } catch (Exception e) {  
  241.             e.printStackTrace();  
  242.         }  
  243.         return rows;  
  244.   
  245.     }  
  246.   
  247.     @Override  
  248.     public int deleteBatch(List<PK> list) {  
  249.         try {  
  250.             return getSqlSession().delete(namespace + "." + SQLID_DELETE_BATCH,list);  
  251.         } catch (Exception e) {  
  252.             e.printStackTrace();  
  253.             return 0;  
  254.         }  
  255.   
  256.     }  
  257.       
  258.     /** 
  259.      * 日志打印 
  260.      * @param sqlId 
  261.      * @param param 
  262.      */  
  263.     public void printLog(String sqlId,Object param){  
  264.         Configuration configuration = getSqlSession().getConfiguration();  
  265.         //sqlId为配置文件中的sqlid  
  266.         MappedStatement mappedStatement = configuration.getMappedStatement(sqlId);  
  267.         //param为传入到sql语句中的参数  
  268.         BoundSql boundSql = mappedStatement.getBoundSql(param);  
  269.         //得到sql语句  
  270.         String sql = boundSql.getSql().trim();  
  271.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  272.         System.out.println("info-sql: "+sdf.format(new Date())+"  "+sql);  
  273.     }  
  274. }  


5,Emp的映射文件

[html] view
plain
copy

  1. <?xml version="1.0" encoding="UTF-8" ?>      
  2. <!DOCTYPE mapper      
  3.     PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"      
  4.     "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  5. <mapper namespace="hwt.Mapper.EmpMapper">  
  6.       
  7.    <!-- 结果集 -->     
  8.    <resultMap id="empResult" type="Emp">   
  9.       <id property="empid" column="empid" />  
  10.       <result property="empname" column="empname"/>  
  11.       <!-- 多对一的关系,注意resultMap的名字为 引用的namespace+resultMap的Id -->  
  12.       <association property="dep" column="depid" javaType="Dep" resultMap="hwt.Mapper.DepMapper.depResult"/>  
  13.    </resultMap>  
  14.      
  15.    <!-- 新增emp实体类 -->  
  16.     <insert id="insert" parameterType="Emp">  
  17.         insert into emp(empid,empname,depid) values(#{empid,jdbcType=INTEGER},#{empname,jdbcType=VARCHAR},#{dep.depid,jdbcType=INTEGER})  
  18.    </insert>  
  19.      
  20.    <!-- 更新对象 -->  
  21.    <update id="update" parameterType="Emp">  
  22.       update emp   
  23.       <set>  
  24.       <if test="empname != null">empname=#{empname,jdbcType=VARCHAR},</if>  
  25.       <if test="dep != null">depid=#{dep.depid,jdbcType=INTEGER},</if>  
  26.       </set>  
  27.       <where>  
  28.         <if test="empid != null">  
  29.             empid = #{empid,jdbcType=INTEGER}  
  30.         </if>  
  31.       </where>  
  32.    </update>  
  33.      
  34.    <!-- 更新对象(参数) -->  
  35.     <update id="updateParam" parameterType="java.util.Map">  
  36.       update emp   
  37.       <set>  
  38.       <if test="empname != null">empname=#{empname,jdbcType=VARCHAR},</if>  
  39.       <if test="dep != null">depid=#{depid,jdbcType=INTEGER},</if>  
  40.       </set>  
  41.       <where>  
  42.         <if test="empid != null">  
  43.             empid = #{empid,jdbcType=INTEGER}  
  44.         </if>  
  45.       </where>  
  46.    </update>  
  47.      
  48.     <!-- 批量更新 -->  
  49.    <update id="updateBatch" parameterType="Emp">  
  50.         <!-- collection可以是List对于list,数组对于array,Map对应ids -->  
  51.         <foreach collection="list" item="emp" separator=";">  
  52.             update emp   
  53.                 <set>  
  54.                    <if test="emp.empname != null">empname= #{emp.empname,jdbcType=VARCHAR},</if>  
  55.                    <if test="emp.dep != null">depid= #{emp.dep.depid,jdbcType=INTEGER},</if>  
  56.                 </set>  
  57.                 <where>  
  58.                     <if test="emp.empid != null">  
  59.                         empid = #{emp.empid,jdbcType=INTEGER}  
  60.                     </if>  
  61.                 </where>  
  62.         </foreach>  
  63.    </update>  
  64.      
  65.    <!-- 根据主键删除 -->  
  66.    <delete id="deletePK" parameterType="int">  
  67.         delete from emp where empid = #{empid}  
  68.    </delete>  
  69.      
  70.    <!-- 根据参数删除 -->  
  71.    <delete id="deleteParam" parameterType="java.util.Map">  
  72.         delete from emp  
  73.         <where>  
  74.             <if test="empname != null">empname = #{empname}</if>  
  75.             <if test="depid != null"> and depid = #{depid}</if>  
  76.             <if test="empid != null"> and empid = #{empid}</if>  
  77.         </where>  
  78.    </delete>  
  79.      
  80.    <!-- 批量删除 -->  
  81.    <delete id="deleteBatch">  
  82.         delete from emp where empid in   
  83.         <trim prefix="(" suffix=")" suffixOverrides=",">  
  84.             <foreach collection="list" item="pk" separator=",">  
  85.                 #{pk}  
  86.             </foreach>  
  87.         </trim>  
  88.    </delete>  
  89.      
  90.    <!-- 批量插入 -->  
  91.    <insert id="insertBatch" parameterType="arraylist">  
  92.         insert into emp(empid,empname,depid)   
  93.         <!-- collection可以是List对于list,数组对于array,Map对应ids -->  
  94.         <foreach collection="list" item="emp"  index="index" separator="union all">  
  95.          select #{emp.empid,jdbcType=NUMERIC},#{emp.empname,jdbcType=VARCHAR},#{emp.dep.depid,jdbcType=NUMERIC} from dual  
  96.         </foreach>  
  97.    </insert>  
  98.      
  99.    <!-- count -->  
  100.    <select id="count" resultType="int">  
  101.         select count(*) from emp e   
  102.   </select>  
  103.   <select id="countParam" parameterType="java.util.Map" resultType="int">  
  104.         select count(*) from emp e   
  105.         <where>  
  106.         <if test="empname != null">empname = #{empname}</if>  
  107.         <if test="depid != null"> and depid = #{depid}</if>  
  108.         <if test="empid != null"> and empid = #{empid}</if>  
  109.        </where>  
  110.   </select>  
  111.     
  112.    <!-- 查询(参数) -->  
  113.    <select id="selectParam" parameterType="java.util.Map" resultType="Emp">  
  114.         select * from emp   
  115.         <where>  
  116.         <if test="empname != null">empname = #{empname}</if>  
  117.         <if test="depid != null"> and depid = #{depid}</if>  
  118.         <if test="empid != null"> and empid = #{empid}</if>  
  119.        </where>  
  120.        <if test="orderColumn != null">  
  121.             order by ${orderColumn}  
  122.             <if test="orderTurn != null">  
  123.                 ${orderTurn}  
  124.             </if>  
  125.        </if>  
  126.    </select>  
  127.      
  128. </mapper> 

抱歉!评论已关闭.