1. 程式人生 > >mybatis整合spring的 泛型DAO介面

mybatis整合spring的 泛型DAO介面

1,使用者分頁的引數類

package hwt.Utils;

import java.util.Map;

public class PageEntity {
	private Integer page; //目前是第幾頁
	private Integer size; //每頁大小
	private Map params; //傳入的引數
	private String orderColumn;
	private String orderTurn = "ASC";
	
	public String getOrderColumn() {
		return orderColumn;
	}
	public void setOrderColumn(String orderColumn) {
		this.orderColumn = orderColumn;
	}
	public String getOrderTurn() {
		return orderTurn;
	}
	public void setOrderTurn(String orderTurn) {
		this.orderTurn = orderTurn;
	}
	public Integer getPage() {
		return page;
	}
	public void setPage(Integer page) {
		this.page = page;
	}
	public Integer getSize() {
		return size;
	}
	public void setSize(Integer size) {
		this.size = size;
	}
	public Map getParams() {
		return params;
	}
	public void setParams(Map params) {
		this.params = params;
	}
}

2,分頁結果類

package hwt.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 分頁結果
 * @author hwt
 *
 */
public class PagingResult<T> {
	//當前頁
	private int currentPage;
	//總共記錄條數
	private int totalSize;
	//結果集
	private List<T> resultList = new ArrayList<T>();
	
	
	public int getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}
	public int getTotalSize() {
		return totalSize;
	}
	public void setTotalSize(int totalSize) {
		this.totalSize = totalSize;
	}
	public List<T> getResultList() {
		return resultList;
	}
	public void setResultList(List<T> resultList) {
		this.resultList = resultList;
	}
}

3,BaseDAO介面
package hwt.DAO;

import hwt.Utils.PageEntity;
import hwt.Utils.PagingResult;

import java.io.Serializable;
import java.util.List;
import java.util.Map;


/**
 * baseDAO
 * @author hwt
 *
 */
public interface BaseDAO<T,PK extends Serializable> {
	
    /**
     * 新增實體
     * @param entity
     * @return 影響記錄條數
     */
    public abstract int insert(T entity);
    
    /** 
     * 修改一個實體物件(UPDATE一條記錄) 
     * @param entity 實體物件 
     * @return 修改的物件個數,正常情況=1 
     */  
    public abstract int update(T entity);  
      
    /** 
     * 修改符合條件的記錄 
     * <p>此方法特別適合於一次性把多條記錄的某些欄位值設定為新值(定值)的情況,比如修改符合條件的記錄的狀態欄位</p> 
     * <p>此方法的另一個用途是把一條記錄的個別欄位的值修改為新值(定值),此時要把條件設定為該記錄的主鍵</p> 
     * @param param 用於產生SQL的引數值,包括WHERE條件、目標欄位和新值等 
     * @return 修改的記錄個數,用於判斷修改是否成功 
     */  
    public abstract int updateParam(Map param);  
      
    /** 
     * 按主鍵刪除記錄 
     * @param primaryKey 主鍵物件 
     * @return 刪除的物件個數,正常情況=1 
     */  
    public abstract int delete(PK primaryKey);  
  
    /** 
     * 刪除符合條件的記錄 
     * <p><strong>此方法一定要慎用,如果條件設定不當,可能會刪除有用的記錄!</strong></p> 
     * @param param 用於產生SQL的引數值,包括WHERE條件(其他引數內容不起作用) 
     * @return 
     */  
    public abstract int deleteParam(Map param);  
      
    /** 
     * 清空表,比delete具有更高的效率,而且是從資料庫中物理刪除(delete是邏輯刪除,被刪除的記錄依然佔有空間) 
     * <p><strong>此方法一定要慎用!</strong></p> 
     * @return 
     */  
    public abstract int truncate();  
      
    /** 
     * 查詢整表總記錄數 
     * @return 整表總記錄數 
     */  
    public abstract int count();  
      
    /** 
     * 查詢符合條件的記錄數 
     * @param param 查詢條件引數,包括WHERE條件(其他引數內容不起作用)。此引數設定為null,則相當於count() 
     * @return 
     */  
    public abstract int count(Object param);  
  
    /** 
     * 按主鍵取記錄 
     * @param primaryKey 主鍵值 
     * @return 記錄實體物件,如果沒有符合主鍵條件的記錄,則返回null 
     */  
    public abstract T get(PK primaryKey);  
  
    /** 
     * 取全部記錄 
     * @return 全部記錄實體物件的List 
     */  
    public abstract List<T> select();  
      
    /** 
     * 按條件查詢記錄 
     * @param param 查詢條件引數,包括WHERE條件、分頁條件、排序條件 
     * @return 符合條件記錄的實體物件的List 
     */  
    public abstract List<T> selectParam(Map param);  
      
    /** 
     * 按條件查詢記錄,並處理成分頁結果 
     * @param param 查詢條件引數,包括WHERE條件、分頁條件、排序條件 
     * @return PaginationResult物件,包括(符合條件的)總記錄數、頁實體物件List等 
     */  
    public abstract PagingResult<T> selectPagination(PageEntity param);  
      
    /** 
     * 批量插入 
     * @param list 
     */  
    public abstract int insertBatch(final List<T> list);  
      
    /** 
     * 批量修改 
     * @param list 
     */  
    public abstract int updateBatch(final List<T> list);  
      
    /** 
     * 批量刪除 
     * @param list 
     */  
    public abstract int deleteBatch(final List<PK> list);  
}

4,BaseDAO的實現類
package hwt.DAO;

import hwt.Utils.PageEntity;
import hwt.Utils.PagingResult;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;

/**
 * baseDAO的實現基類
 * 
 * @author hwt
 * 
 * @param <T>
 * @param <PK>
 */
public class BaseDaoImpl<T, PK extends Serializable> extends
		SqlSessionDaoSupport implements BaseDAO<T, PK> {
	// mapper.xml中的namespace
	private String namespace;

	// sqlmap.xml定義檔案中對應的sqlid
	public static final String SQLID_INSERT = "insert";
	public static final String SQLID_INSERT_BATCH = "insertBatch";
	public static final String SQLID_UPDATE = "update";
	public static final String SQLID_UPDATE_PARAM = "updateParam";
	public static final String SQLID_UPDATE_BATCH = "updateBatch";
	public static final String SQLID_DELETE = "delete";
	public static final String SQLID_DELETE_PARAM = "deleteParam";
	public static final String SQLID_DELETE_BATCH = "deleteBatch";
	public static final String SQLID_TRUNCATE = "truncate";
	public static final String SQLID_SELECT = "select";
	public static final String SQLID_SELECT_PK = "selectPk";
	public static final String SQLID_SELECT_PARAM = "selectParam";
	public static final String SQLID_SELECT_FK = "selectFk";
	public static final String SQLID_COUNT = "count";
	public static final String SQLID_COUNT_PARAM = "countParam";

	@Resource(name = "sqlSessionTemplate")
	public void setSuperSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		super.setSqlSessionTemplate(sqlSessionTemplate);
	}

	public String getNamespace() {
		return namespace;
	}

	public void setNamespace(String namespace) {
		this.namespace = namespace;
	}

	@Override
	public int insert(T entity) {
		int rows = 0;
		try {
			rows = getSqlSession().insert(namespace + "." + SQLID_INSERT,
					entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rows;
	}

	@Override
	public int update(T entity) {
		int rows = 0;
		try {
			rows = getSqlSession().update(namespace + "." + SQLID_UPDATE,
					entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rows;
	}

	@Override
	public int updateParam(Map param) {
		int rows = 0;
		try {
			rows = getSqlSession().update(namespace + "." + SQLID_UPDATE_PARAM,
					param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rows;
	}

	@Override
	public int delete(PK primaryKey) {
		int rows = 0;
		try {
			rows = getSqlSession().delete(namespace + "." + SQLID_DELETE,
					primaryKey);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rows;
	}

	@Override
	public int deleteParam(Map param) {
		int rows = 0;
		try {
			rows = getSqlSession().delete(namespace + "." + SQLID_DELETE_PARAM,
					param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rows;
	}

	@Override
	public int truncate() {
		int rows = 0;
		try {
			rows = getSqlSession().delete(namespace + "." + SQLID_TRUNCATE);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rows;
	}

	@Override
	public int count() {
		int result = 0;
		try {
			result = getSqlSession().selectOne(namespace + "." + SQLID_COUNT);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public int count(Object param) {
		int result = 0;
		try {
			result = getSqlSession().selectOne(namespace + "." + SQLID_COUNT_PARAM,param);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public T get(PK primaryKey) {
		try {
			return getSqlSession().selectOne(namespace + "." + SQLID_SELECT_PK,primaryKey);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public List<T> select() {
		try {
			return getSqlSession().selectList(namespace + "." + SQLID_SELECT);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}

	@Override
	public List<T> selectParam(Map param) {
		try {
			return getSqlSession().selectList(namespace + "." + SQLID_SELECT_PARAM,param);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public PagingResult<T> selectPagination(PageEntity pageEntity) {
		try {
			int page = pageEntity.getPage() == null || "".equals(pageEntity.getPage()) ? 1 : pageEntity.getPage(); //預設為第一頁
			int size = pageEntity.getSize() == null || "".equals(pageEntity.getSize()) ? 15 : pageEntity.getSize();; //預設每頁15個
			
			RowBounds rowBounds = new RowBounds((page-1)*size, size);
			
			Map param = pageEntity.getParams();
			if (param != null) {
				param.put("orderColumn", pageEntity.getOrderColumn());
				param.put("orderTurn", pageEntity.getOrderTurn());
			}else {
				param = new HashMap();
				param.put("orderColumn", pageEntity.getOrderColumn());
				param.put("orderTurn", pageEntity.getOrderTurn());
			}
			
			List<T> resultList = getSqlSession().selectList(namespace + "." + SQLID_SELECT_PARAM,param,rowBounds);
			int totalSize = count(pageEntity.getParams());
			
			PagingResult<T> pagingResult = new PagingResult<T>();
			pagingResult.setCurrentPage(page);
			pagingResult.setTotalSize(totalSize);
			pagingResult.setResultList(resultList);
			return pagingResult;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}


	@Override
	public int insertBatch(List<T> list) {
		try {
			return getSqlSession().insert(namespace + "." + SQLID_INSERT_BATCH,list);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}
 
	@Override
	public int updateBatch(List<T> list) {
		int rows = 0;
		try {
			for (T t : list) {
				rows = rows + getSqlSession().update(namespace + "." + SQLID_UPDATE, t);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rows;

	}

	@Override
	public int deleteBatch(List<PK> list) {
		try {
			return getSqlSession().delete(namespace + "." + SQLID_DELETE_BATCH,list);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}

	}
	
	/**
	 * 日誌列印
	 * @param sqlId
	 * @param param
	 */
	public void printLog(String sqlId,Object param){
		Configuration configuration = getSqlSession().getConfiguration();
		//sqlId為配置檔案中的sqlid
		MappedStatement mappedStatement = configuration.getMappedStatement(sqlId);
		//param為傳入到sql語句中的引數
		BoundSql boundSql = mappedStatement.getBoundSql(param);
		//得到sql語句
		String sql = boundSql.getSql().trim();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("info-sql: "+sdf.format(new Date())+"  "+sql);
	}
}

5,Emp的對映檔案
<?xml version="1.0" encoding="UTF-8" ?>    
<!DOCTYPE mapper    
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"    
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="hwt.Mapper.EmpMapper">
    
   <!-- 結果集 -->	
   <resultMap id="empResult" type="Emp"> 
	  <id property="empid" column="empid" />
	  <result property="empname" column="empname"/>
	  <!-- 多對一的關係,注意resultMap的名字為 引用的namespace+resultMap的Id -->
	  <association property="dep" column="depid" javaType="Dep" resultMap="hwt.Mapper.DepMapper.depResult"/>
   </resultMap>
   
   <!-- 新增emp實體類 -->
    <insert id="insert" parameterType="Emp">
   		insert into emp(empid,empname,depid) values(#{empid,jdbcType=INTEGER},#{empname,jdbcType=VARCHAR},#{dep.depid,jdbcType=INTEGER})
   </insert>
   
   <!-- 更新物件 -->
   <update id="update" parameterType="Emp">
   	  update emp 
   	  <set>
      <if test="empname != null">empname=#{empname,jdbcType=VARCHAR},</if>
      <if test="dep != null">depid=#{dep.depid,jdbcType=INTEGER},</if>
      </set>
      <where>
      	<if test="empid != null">
      		empid = #{empid,jdbcType=INTEGER}
      	</if>
      </where>
   </update>
   
   <!-- 更新物件(引數) -->
    <update id="updateParam" parameterType="java.util.Map">
   	  update emp 
   	  <set>
      <if test="empname != null">empname=#{empname,jdbcType=VARCHAR},</if>
      <if test="dep != null">depid=#{depid,jdbcType=INTEGER},</if>
      </set>
      <where>
      	<if test="empid != null">
      		empid = #{empid,jdbcType=INTEGER}
      	</if>
      </where>
   </update>
   
    <!-- 批量更新 -->
   <update id="updateBatch" parameterType="Emp">
        <!-- collection可以是List對於list,陣列對於array,Map對應ids -->
        <foreach collection="list" item="emp" separator=";">
   			update emp 
		   		<set>
		   		   <if test="emp.empname != null">empname= #{emp.empname,jdbcType=VARCHAR},</if>
		           <if test="emp.dep != null">depid= #{emp.dep.depid,jdbcType=INTEGER},</if>
		   		</set>
		   		<where>
			      	<if test="emp.empid != null">
			      		empid = #{emp.empid,jdbcType=INTEGER}
			      	</if>
			    </where>
   		</foreach>
   </update>
   
   <!-- 根據主鍵刪除 -->
   <delete id="deletePK" parameterType="int">
   		delete from emp where empid = #{empid}
   </delete>
   
   <!-- 根據引數刪除 -->
   <delete id="deleteParam" parameterType="java.util.Map">
   		delete from emp
   		<where>
   			<if test="empname != null">empname = #{empname}</if>
	   		<if test="depid != null"> and depid = #{depid}</if>
	      	<if test="empid != null"> and empid = #{empid}</if>
   		</where>
   </delete>
   
   <!-- 批量刪除 -->
   <delete id="deleteBatch">
   		delete from emp where empid in 
   		<trim prefix="(" suffix=")" suffixOverrides=",">
   			<foreach collection="list" item="pk" separator=",">
   				#{pk}
   			</foreach>
   		</trim>
   </delete>
   
   <!-- 批量插入 -->
   <insert id="insertBatch" parameterType="arraylist">
        insert into emp(empid,empname,depid) 
        <!-- collection可以是List對於list,陣列對於array,Map對應ids -->
   		<foreach collection="list" item="emp"  index="index" separator="union all">
   		 select #{emp.empid,jdbcType=NUMERIC},#{emp.empname,jdbcType=VARCHAR},#{emp.dep.depid,jdbcType=NUMERIC} from dual
   		</foreach>
   </insert>
   
   <!-- count -->
   <select id="count" resultType="int">
		select count(*) from emp e 
  </select>
  <select id="countParam" parameterType="java.util.Map" resultType="int">
		select count(*) from emp e 
		<where>
   		<if test="empname != null">empname = #{empname}</if>
   		<if test="depid != null"> and depid = #{depid}</if>
      	<if test="empid != null"> and empid = #{empid}</if>
       </where>
  </select>
  
   <!-- 查詢(引數) -->
   <select id="selectParam" parameterType="java.util.Map" resultType="Emp">
   		select * from emp 
   		<where>
   		<if test="empname != null">empname = #{empname}</if>
   		<if test="depid != null"> and depid = #{depid}</if>
      	<if test="empid != null"> and empid = #{empid}</if>
       </where>
       <if test="orderColumn != null">
       		order by ${orderColumn}
       		<if test="orderTurn != null">
       			${orderTurn}
       		</if>
       </if>
   </select>
   
</mapper>