1. 程式人生 > >基於springboot+bootstrap+mysql+redis搭建一套完整的許可權架構【四】【編寫基礎開發工具】

基於springboot+bootstrap+mysql+redis搭建一套完整的許可權架構【四】【編寫基礎開發工具】

       大家在經過一段時間的開發實際上已經積累的自己的一套的開發框架或者一些自己的jar包,此處所編寫的開發工具是基於當前工程的進行擴充套件的一個開發工具包,僅適合當前框架,若大家需要的話可以自己在當前開發工具包底下進行擴充套件,有了開發工具包的好處就是我們可以少寫很多基礎的程式碼,那麼接下來將開始編寫我們的開發工具包:

      首先在我們的common包底下先建以下的包結構:


在我們建立我們的開發工具包之前我們需要先新增幾個配置檔案在我們的config->util包底下我們建立一個json包同時增加一個JsonHelper.java檔案如下所示:

/*
* 類描述:json工具類
* @auther linzf
* @create 2017/8/23 0023 
*/
public class JsonHelper {

    private static SimpleDateFormat sdf = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    // 將JSON轉換成Map,其中valueClz為Map中value的Class,keyArray為Map的key
    public static Map json2Map(Object[] keyArray, String json, Class valueClz) {
        JSONObject jsonObject = JSONObject.fromObject(json);
        Map classMap = new HashMap();
        for (int i = 0; i < keyArray.length; i++) {
            classMap.put(keyArray[i], valueClz);
        }
        return (Map) JSONObject.toBean(jsonObject, Map.class, classMap);
    }

    /***
     * 將物件轉換為傳入型別的List
     *
     * @param object
     * @param objectClass
     * @return
     */
    public static <T> Collection<T> toList(Object object, Class<T> objectClass) {
        JSONArray jsonArray = JSONArray.fromObject(object);
        return JSONArray.toCollection(jsonArray, objectClass);
    }

    /**
     * 功能描述:實現將一個object物件轉換為json的string字串
     * @param obj
     * @return
     */
    public static String object2json(Object obj) {
        StringBuilder json = new StringBuilder();
        if (obj == null) {
            json.append("\"\"");
        } else if (obj instanceof String || obj instanceof BigDecimal
                || obj instanceof BigInteger) {
            json.append("\"").append(string2json(obj.toString())).append("\"");
        } else if (obj instanceof Boolean) {
            json.append(Boolean.valueOf(obj.toString()));
        } else if (obj instanceof Integer || obj instanceof Float
                || obj instanceof Short || obj instanceof Double
                || obj instanceof Long || obj instanceof Byte) {
            json.append(obj.toString());
        } else if (obj instanceof Date || obj instanceof java.sql.Date) {
            json.append("\"").append(sdf.format(obj)).append("\"");
        } else if (obj instanceof Object[]) {
            json.append(array2json((Object[]) obj));
        } else if (obj instanceof List) {
            json.append(list2json((List<?>) obj));
        } else if (obj instanceof Map) {
            json.append(map2json((Map<?, ?>) obj));
        } else if (obj instanceof Set) {
            json.append(set2json((Set<?>) obj));
        } else {
            json.append(bean2json(obj));
        }
        return json.toString();
    }

    public static String list2json(List<?> list) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (list != null && list.size() > 0) {
            for (Object obj : list) {
                json.append(object2json(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, ']');
        } else {
            json.append("]");
        }
        return json.toString();
    }

    public static String array2json(Object[] array) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (array != null && array.length > 0) {
            for (Object obj : array) {
                json.append(object2json(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, ']');
        } else {
            json.append("]");
        }
        return json.toString();
    }

    public static String map2json(Map<?, ?> map) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        if (map != null && map.size() > 0) {
            for (Object key : map.keySet()) {
                json.append(object2json(key));
                json.append(":");
                json.append(object2json(map.get(key)));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, '}');
        } else {
            json.append("}");
        }
        return json.toString();
    }

    public static String set2json(Set<?> set) {
        StringBuilder json = new StringBuilder();
        json.append("[");
        if (set != null && set.size() > 0) {
            for (Object obj : set) {
                json.append(object2json(obj));
                json.append(",");
            }
            json.setCharAt(json.length() - 1, ']');
        } else {
            json.append("]");
        }
        return json.toString();
    }

    public static String string2json(String s) {
        if (s == null)
            return "";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            switch (ch) {
                case '"':
                    sb.append("\\\"");
                    break;
                case '\\':
                    sb.append("\\\\");
                    break;
                case '\b':
                    sb.append("\\b");
                    break;
                case '\f':
                    sb.append("\\f");
                    break;
                case '\n':
                    sb.append("\\n");
                    break;
                case '\r':
                    sb.append("\\r");
                    break;
                case '\t':
                    sb.append("\\t");
                    break;
                case '/':
                    sb.append("\\/");
                    break;
                default:
                    if (ch >= '\u0000' && ch <= '\u001F') {
                        String ss = Integer.toHexString(ch);
                        sb.append("\\u");
                        for (int k = 0; k < 4 - ss.length(); k++) {
                            sb.append('0');
                        }
                        sb.append(ss.toUpperCase());
                    } else {
                        sb.append(ch);
                    }
            }
        }
        return sb.toString();
    }

    public static String bean2json(Object bean) {
        StringBuilder json = new StringBuilder();
        json.append("{");
        PropertyDescriptor[] props = null;
        try {
            props = Introspector.getBeanInfo(bean.getClass(), Object.class)
                    .getPropertyDescriptors();
        } catch (IntrospectionException e) {
        }
        if (props != null) {
            for (int i = 0; i < props.length; i++) {
                try {
                    String name = object2json(props[i].getName());
                    String value = object2json(props[i].getReadMethod().invoke(
                            bean));
                    json.append(name);
                    json.append(":");
                    json.append(value);
                    json.append(",");
                } catch (Throwable e) {
                }
            }
            json.setCharAt(json.length() - 1, '}');
        } else {
            json.append("}");
        }
        return json.toString();
    }


}


接著我們在dao,entity,service包底下分別加入以下的類檔案:

/**
 * 分頁實體類
 * */
@SuppressWarnings("rawtypes")
public class Page {
	private List rows;
	private long total;
	
	public Page(){}
	
	public Page(List rows, long total) {
		super();
		this.rows = rows;
		this.total = total;
	}
	
	public List getRows() {
		return rows;
	}
	public void setRows(List rows) {
		this.rows = rows;
	}
	public long getTotal() {
		return total;
	}
	public void setTotal(long total) {
		this.total = total;
	}

	@Override
	public String toString() {
		return "Page [rows=" + rows + ", total=" + total + "]";
	}
}

/*
* 類描述:查詢基礎類
* @auther linzf
* @create 2017/8/11 0011 
*/
public class QueryBase {

    /** 要排序的欄位名 */
    protected String sort;
    /** 排序方式: desc \ asc */
    protected String order = "";
    /** 獲取一頁行數 */
    protected int limit;
    /** 獲取的頁碼 */
    protected int page;
    /** 起始記錄 */
    protected int offset;

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    public String getOrder() {
        return order;
    }

    public void setOrder(String order) {
        this.order = order;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getOffset() {
        return (this.page-1)*limit;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }
}

/**
 * Dao通用模版
 * */
public interface GenericDao<T, Q extends QueryBase>{
	/**
	 * 根據主鍵值獲取物件
	 * @param entity
	 * */
	public T get(T entity);
	
	/**
	 * 獲取全部實體
	 * */
    public List<T> loadAll();

	/**
	 * 查詢是否存在
	 * @param queryModel 查詢條件
	 * @return int
	 * */
	public int isExist(Q queryModel);

	/** 
	 * 儲存
	 * @param entity 儲存物件
	 * @return int
	 * @throws Exception
	 * */
	public int save(T entity) throws Exception;

	/** 
	 * 更新 
	 * @param entity 修改物件
	 * @return int
	 * @throws Exception
	 * */
	public int update(T entity) throws Exception;

	/**
	 * 刪除 
	 * @param entity 刪除物件
	 * @throws Exception
	 * @return int
	 * */
	public int delete(T entity) throws Exception;

	/**
	 * 分頁查詢
	 * @param queryModel 查詢條件
	 *  */
	public List<T> findByPage(Q queryModel);
	
	/**
	 * 統計
	 * @param queryModel 查詢條件
	 * @return int
	 * */
	public int count(Q queryModel);

	/**
	 * 查詢
	 * @param queryModel 查詢條件
	 *  */
	public List<T> query(Q queryModel);
	/**
	 * 根據id陣列刪除記錄
	 * @param ids 陣列
	 * @return int
	 * */
	public int deleteByIds(String[] ids) throws Exception;
}

/**
 * 通用Service
 * @author linzf
 * */
public abstract class GenericService<T, Q extends QueryBase> {
	protected abstract GenericDao<T, Q> getDao();
	
	/**
	 * 根據主鍵值獲取物件
	 * @param entity
	 * */
	public T get(T entity){
		return getDao().get(entity);
	}

	/**
	 * 獲取全部實體
	 * */
    public List<T> loadAll(){
    	return getDao().loadAll();
    }

	/**
	 * 查詢是否存在
	 * @param queryModel 查詢條件
	 * */
	public boolean isExist(Q queryModel){
		return getDao().isExist(queryModel)>0;
	}

	/** 
	 * 儲存
	 * @param entity 儲存物件
	 * @return boolean
	 * @throws Exception
	 * */
	public boolean save(T entity) throws Exception{
		return getDao().save(entity)>0;
	}

	/** 
	 * 更新 
	 * @param entity 修改物件
	 * @return boolean
	 * @throws Exception
	 * */
	public boolean update(T entity) throws Exception{
		return getDao().update(entity)>0;
	}

	/**
	 * 刪除 
	 * @param entity 刪除物件
	 * @return boolean
	 * @throws Exception
	 * */
	public boolean delete(T entity) throws Exception{
		return getDao().delete(entity)>0;
	}

	/**
	 * 分頁查詢
	 * @param queryModel 查詢條件
	 *  */
	public Page findByPage(Q queryModel){
		List<T> list =  getDao().findByPage(queryModel);
		int count = getDao().count(queryModel);
		return new Page(list, count);
	}
	
	/**
	 * 統計
	 * @param queryModel 查詢條件
	 * @return int
	 * */
	public int count(Q queryModel){
		return getDao().count(queryModel);
	}

	/**
	 * 查詢
	 * @param queryModel 查詢條件
	 *  */
	public List<T> query(Q queryModel){
		return getDao().query(queryModel);
	}
	/**
	 * 根據id陣列刪除記錄
	 * @param ids 陣列
	 * @return boolean
	 * */
	public boolean deleteByIds(String[] ids) throws Exception{
		return getDao().deleteByIds(ids)>0;
	}

	/**
	 * 功能描述:批量刪除資料
	 * @param entityList
	 * @return
	 */
	public boolean removeBath(List<T> entityList) throws Exception{
		for(T t:entityList){
			if(!delete(t)){
				return false;
			}
		}
       return true;
	}
}
public abstract class GenericController<T, Q extends QueryBase> {

	// 抽象方法
	protected abstract GenericService<T, Q> getService();

	/**新增頁面路徑*/
	public final static String ADDPAGE = "/add";
	/**修改頁面路徑*/
	public final static String UPDATEPAGE = "/update";

	/**
	 * Controller基路徑
	 * */
	protected String basePath;

	/**抽象方法,獲取頁面基路徑
	 * @throws Exception */
	protected String getPageBaseRoot() throws Exception{
		if(basePath==null){
			basePath = this.getClass().getName();
			Pattern p=Pattern.compile(".[a-z|A-z]+.controller.[a-z|A-z]+Controller");
			Matcher m=p.matcher(basePath);
			if(m.find()){
				basePath = m.group();
				basePath = basePath.substring(1, basePath.length()-10);
				basePath = basePath.replace(".", "/");
				basePath = basePath.replace("/controller/", "/");
				basePath = basePath.substring(0,basePath.lastIndexOf("/")+1)+ toFirstCharLowerCase(basePath.substring(basePath.lastIndexOf("/")+1));
			}
			else{
				throw new Exception("獲取頁面基路徑失敗");
			}
		}
		return basePath;
	}


	/**
	 * 功能描述:直接跳轉到更新資料的頁面
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/updatePage",method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
	public String updatePage(T entity,Model model) throws Exception{
		entity = getService().get(entity);
		model.addAttribute("entity",entity);
		return getPageBaseRoot()+UPDATEPAGE;
	}

	/** 跳轉到新增物件頁面
	 * @throws Exception */
	@RequestMapping(value="/addPage")
	public String addPage() throws Exception{
		return getPageBaseRoot()+ADDPAGE;
	}

	/**
	 * 功能描述:儲存資料字典資料
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/save",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map<String,Object> save(T entity) throws Exception{
		boolean success = getService().save(entity);
		Map<String,Object> result = new HashMap<String, Object>();
		if(success==true){
			result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
			result.put(SystemStaticConst.MSG,"增加資料成功!");
			result.put("entity",entity);
		}else{
			result.put(SystemStaticConst.RESULT,SystemStaticConst.FAIL);
			result.put(SystemStaticConst.MSG,"增加資料失敗!");
		}
		return result;
	}

	/**
	 * 功能描述:更新資料字典資料
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/update",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map<String,Object> update(T entity)  throws Exception{
		boolean success  = getService().update(entity);
		Map<String,Object> result = new HashMap<String, Object>();
		if(success==true){
			result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
			result.put(SystemStaticConst.MSG,"更新資料成功!");
			result.put("entity",entity);
		}else{
			result.put(SystemStaticConst.RESULT,SystemStaticConst.FAIL);
			result.put(SystemStaticConst.MSG,"更新資料失敗!");
		}
		return result;
	}

	/**
	 * 功能描述:實現批量刪除資料字典的記錄
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/remove",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map<String,Object> remove(T entity) throws Exception{
		Map<String,Object> result = new HashMap<String, Object>();
		getService().delete(entity);
		result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
		result.put(SystemStaticConst.MSG,"刪除資料成功!");
		return result;
	}


	/**
	 * 功能描述:實現批量刪除資料字典的記錄
	 * @param json
	 * @return
	 */
	@RequestMapping(value = "/removeBath",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map<String,Object> removeBath(String json) throws Exception{
		Map<String,Object> result = new HashMap<String, Object>();
		getService().removeBath((List<T>) JsonHelper.toList(json,(Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]));
		result.put(SystemStaticConst.RESULT,SystemStaticConst.SUCCESS);
		result.put(SystemStaticConst.MSG,"刪除資料成功!");
		return result;
	}

	/**
	 * 功能描述:獲取資料字典的分頁的資料
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/list",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map<String,Object> list(Q entity){
		Map<String,Object> result = new HashMap<String, Object>();
		Page page = getService().findByPage(entity);
		result.put("totalCount",page.getTotal());
		result.put("result",page.getRows());
		return result;
	}

	/**
	 * 功能描述:判斷當前的字典元素是否已經存在
	 * @param entity
	 * @return
	 */
	@RequestMapping(value = "/isExist",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Map<String,Object> isExist(Q entity){
		Map<String,Object> result = new HashMap<String, Object>();
		if(getService().query(entity).size()>0){
			result.put("valid",false);
		}else{
			result.put("valid",true);
		}
		return result;
	}

	/**
	 * 將首字母變小寫
	 * @param str
	 * @return
	 */
	private static String toFirstCharLowerCase(String str){
		char[]  columnCharArr = str.toCharArray();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < columnCharArr.length; i++) {
			char cur = columnCharArr[i];
			if(i==0){
				sb.append(Character.toLowerCase(cur));
			}else{
				sb.append(cur);
			}
		}
		return sb.toString();
	}

}

新增好上面的實體以後我們就完成了我們開發基礎工具類的基本工作,效果如下所示:


接著我們改造我們之前的使用者模組的程式碼,先開啟我們的mybatis->mapper底下的mybatis_user.xml我們重新改造該檔案結果如下:

<?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="com.csdn.demo.sys.dao.UserDao">

	<resultMap type="com.csdn.demo.sys.entity.User" id="UserMap">
		<id property="id" column="id"/>
		<result property="login" column="login"/>
		<result property="password" column="password"/>
		<result property="userName" column="user_name"/>
		<result property="address" column="address"/>
		<result property="job" column="job"/>
		<result property="groupId" column="group_id"/>
		<result property="birthDate" column="birth_date"/>
		<result property="city" column="city"/>
		<result property="district" column="district"/>
		<result property="province" column="province"/>
		<result property="streetAddress" column="street_address"/>
		<result property="state" column="state"/>
		<result property="type" column="type"/>
		<result property="lastLoginDate" column="last_login_date"/>
	</resultMap>

	<!-- 包含角色資訊的map -->
	<resultMap type="com.csdn.demo.sys.entity.User" id="UserLoginMap">
		<id property="id" column="id"/>
		<result property="login" column="login"/>
		<result property="password" column="password"/>
		<result property="userName" column="user_name"/>
		<result property="address" column="address"/>
		<result property="job" column="job"/>
		<result property="groupId" column="group_id"/>
		<result property="birthDate" column="birth_date"/>
		<result property="city" column="city"/>
		<result property="district" column="district"/>
		<result property="province" column="province"/>
		<result property="streetAddress" column="street_address"/>
		<result property="state" column="state"/>
		<result property="type" column="type"/>
		<result property="lastLoginDate" column="last_login_date"/>
		<collection property="roles"  ofType="com.csdn.demo.sys.entity.UserRole" javaType="java.util.ArrayList">
			<result column="user_role_id" property="id" jdbcType="VARCHAR" />
			<result column="name" property="name" jdbcType="VARCHAR" />
			<result column="role_name" property="roleName" jdbcType="VARCHAR" />
		</collection>
	</resultMap>

	<!-- 根據賬號來獲取使用者資訊 -->
	<select id="findByLogin" parameterType="java.lang.String" resultMap="UserLoginMap">
		select u.*,ur.id as user_role_id,ur.name,ur.role_name from user u inner join user_associate_role uar on u.id = uar.user_id inner join user_role ur on uar.role_id = ur.id where u.login = #{login}
	</select>

	<!--根據主鍵獲取物件-->
	<select id="get" parameterType="com.csdn.demo.sys.entity.User" resultMap="UserMap">
		select u.* from user u
		WHERE id=#{id}
	</select>

	<!--儲存-->
	<insert id="save" parameterType="com.csdn.demo.sys.entity.User" useGeneratedKeys="true" keyProperty="id">
		INSERT INTO user(login,password,user_name,address,job,group_id,birth_date,city,district,province,street_address,state,type,last_login_date)
		VALUES(#{login},#{password},#{userName},#{address},#{job},#{orgGroup.groupId},#{birthDate},#{city},#{district},#{province},#{streetAddress},#{state},#{type},#{lastLoginDate})
	</insert>

	<!--修改-->
	<update id="update" parameterType="com.csdn.demo.sys.entity.User">
		UPDATE user SET user_name=#{userName},address=#{address},job=#{job},group_id=#{orgGroup.groupId},birth_date=#{birthDate},city=#{city},district=#{district},province=#{province},street_address=#{streetAddress}
		WHERE id=#{id}
	</update>

	<!--刪除-->
	<delete id="delete" parameterType="com.csdn.demo.sys.entity.User">
		DELETE FROM user WHERE id=#{id}
	</delete>

	<!--分頁查詢組織架構底下的使用者-->
	<select id="findGroupUserByPage" parameterType="com.csdn.demo.sys.entity.QueryUser" resultMap="UserMap">
		select u.* from user u
		WHERE 1=1
		<if test="userName!=null and userName!='' ">
			AND u.user_name like concat(#{userName},'%')
		</if>
		<if test="sort!= null and sort!='' ">
			order by ${sort} ${order}
		</if>
		limit #{offset},#{limit}
	</select>

	<!--統計組織架構底下的使用者-->
	<select id="countGroupUser" parameterType="com.csdn.demo.sys.entity.QueryUser" resultType="int">
		select count(1) from user u
		WHERE 1=1
		<if test="userName!=null and userName!='' ">
			AND u.user_name like concat(#{userName},'%')
		</if>
	</select>

	<!--分頁查詢-->
	<select id="findByPage" parameterType="com.csdn.demo.sys.entity.QueryUser" resultMap="UserMap">
		select u.* from user u
		WHERE 1=1
		<if test="login!=null and login!='' ">
			AND u.login=#{login}
		</if>
		<if test="password!=null and password!='' ">
			AND u.password=#{password}
		</if>
		<if test="userName!=null and userName!='' ">
			AND u.user_name=#{userName}
		</if>
		<if test="address!=null and address!='' ">
			AND u.address=#{address}
		</if>
		<if test="job!=null and job!='' ">
			AND u.job=#{job}
		</if>
		<if test="groupId!=null and groupId!='' ">
			AND u.group_id=#{groupId}
		</if>
		<if test="birthDate!=null and birthDate!='' ">
			AND u.birth_date=#{birthDate}
		</if>
		<if test="city!=null and city!='' ">
			AND u.city=#{city}
		</if>
		<if test="district!=null and district!='' ">
			AND u.district=#{district}
		</if>
		<if test="province!=null and province!='' ">
			AND u.province=#{province}
		</if>
		<if test="streetAddress!=null and streetAddress!='' ">
			AND u.street_address=#{streetAddress}
		</if>
		<if test="state!=null and state!='' ">
			AND u.state=#{state}
		</if>
		<if test="type!=null and type!='' ">
			AND u.type=#{type}
		</if>
		<if test="lastLoginDate!=null and lastLoginDate!='' ">
			AND u.last_login_date=#{lastLoginDate}
		</if>
		<if test="sort!= null and sort!='' ">
			order by ${sort} ${order}
		</if>
		limit #{offset},#{limit}
	</select>

	<!--統計-->
	<select id="count" parameterType="com.csdn.demo.sys.entity.QueryUser" resultType="int">
		SELECT count(*) FROM user
		WHERE 1=1
		<if test="login!=null and login!='' ">
			AND login=#{login}
		</if>
		<if test="password!=null and password!='' ">
			AND password=#{password}
		</if>
		<if test="userName!=null and userName!='' ">
			AND user_name=#{userName}
		</if>
		<if test="address!=null and address!='' ">
			AND address=#{address}
		</if>
		<if test="job!=null and job!='' ">
			AND job=#{job}
		</if>
		<if test="groupId!=null and groupId!='' ">
			AND group_id=#{groupId}
		</if>
		<if test="birthDate!=null and birthDate!='' ">
			AND birth_date=#{birthDate}
		</if>
		<if test="city!=null and city!='' ">
			AND city=#{city}
		</if>
		<if test="district!=null and district!='' ">
			AND district=#{district}
		</if>
		<if test="province!=null and province!='' ">
			AND province=#{province}
		</if>
		<if test="streetAddress!=null and streetAddress!='' ">
			AND street_address=#{streetAddress}
		</if>
		<if test="state!=null and state!='' ">
			AND state=#{state}
		</if>
		<if test="type!=null and type!='' ">
			AND type=#{type}
		</if>
		<if test="lastLoginDate!=null and lastLoginDate!='' ">
			AND last_login_date=#{lastLoginDate}
		</if>
		<if test="sort!= null and sort!='' ">
			order by ${sort} ${order}
		</if>
	</select>

	<!--查詢-->
	<select id="query" parameterType="com.csdn.demo.sys.entity.QueryUser" resultMap="UserMap">
		SELECT id,login,password,user_name,address,job,group_id,birth_date,city,district,province,street_address,state,type,last_login_date FROM user
		WHERE 1=1
		<if test="login!=null and login!='' ">
			AND login=#{login}
		</if>
		<if test="password!=null and password!='' ">
			AND password=#{password}
		</if>
		<if test="userName!=null and userName!='' ">
			AND user_name=#{userName}
		</if>
		<if test="address!=null and address!='' ">
			AND address=#{address}
		</if>
		<if test="job!=null and job!='' ">
			AND job=#{job}
		</if>
		<if test="groupId!=null and groupId!='' ">
			AND group_id=#{groupId}
		</if>
		<if test="birthDate!=null and birthDate!='' ">
			AND birth_date=#{birthDate}
		</if>
		<if test="city!=null and city!='' ">
			AND city=#{city}
		</if>
		<if test="district!=null and district!='' ">
			AND district=#{district}
		</if>
		<if test="province!=null and province!='' ">
			AND province=#{province}
		</if>
		<if test="streetAddress!=null and streetAddress!='' ">
			AND street_address=#{streetAddress}
		</if>
		<if test="state!=null and state!='' ">
			AND state=#{state}
		</if>
		<if test="type!=null and type!='' ">
			AND type=#{type}
		</if>
		<if test="lastLoginDate!=null and lastLoginDate!='' ">
			AND last_login_date=#{lastLoginDate}
		</if>
		<if test="sort!= null and sort!='' ">
			order by ${sort} ${order}
		</if>
	</select>

</mapper>



接著改造我們的java層,首先在我們的sys包的entity底下建立一個QueryUser.java檔案如下所示:

/**
 *@author linzf
 **/
public class QueryUser extends QueryBase {
	private String login;
	private String password;
	private String userName;
	private String address;
	private String job;
	private Long groupId;
	private String birthDate;
	private String city;
	private String district;
	private String province;
	private String streetAddress;
	private String state;
	private String type;
	private String lastLoginDate;


	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getJob() {
		return job;
	}

	public void setJob(String job) {
		this.job = job;
	}

	public Long getGroupId() {
		return groupId;
	}

	public void setGroupId(Long groupId) {
		this.groupId = groupId;
	}

	public String getBirthDate() {
		return birthDate;
	}

	public void setBirthDate(String birthDate) {
		this.birthDate = birthDate;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getDistrict() {
		return district;
	}

	public void setDistrict(String district) {
		this.district = district;
	}

	public String getProvince() {
		return province;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public String getStreetAddress() {
		return streetAddress;
	}

	public void setStreetAddress(String streetAddress) {
		this.streetAddress = streetAddress;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getLastLoginDate() {
		return lastLoginDate;
	}

	public void setLastLoginDate(String lastLoginDate) {
		this.lastLoginDate = lastLoginDate;
	}

}
接著改造我們的UserDao如下所示:
/**
 *@author linzf
 **/
public interface UserDao extends GenericDao<User, QueryUser> {

    /**
     * 功能描述:根據賬號來獲取使用者資訊
     * @param login
     * @return
     */
    User findByLogin(String login);

	
}
接著在sys包底下建立一個service包,並建立UserService.java檔案如下所示:
/*
* 類描述:
* @auther linzf
* @create 2017/12/8 0008 
*/
@Service("userService")
@Transactional(rollbackFor={IllegalArgumentException.class})
public class UserService extends GenericService<User, QueryUser> {


    @Autowired
    @SuppressWarnings("SpringJavaAutowiringInspection")
    private UserDao userDao;

    @Override
    protected GenericDao<User, QueryUser> getDao() {
        return userDao;
    }
}

接著改造我們的controller層程式碼如下:
/*
* 類描述:使用者維護controller
* @auther linzf
* @create 2017/9/7 0007
*/
@Controller
@RequestMapping("/user")
public class UserController extends GenericController<User,QueryUser> {

    @Inject
    private UserService userService;
    
    @Override
    protected GenericService<User, QueryUser> getService() {
        return userService;
    }
}

配置好以後我們的整個的效果如下:


接著我們重新載入我們的程式碼並把整個專案執行起來,然後去訪問我們的swagger2的目錄,你會發現我們已經多了很多的功能了,以後我們有了新的模組的時候我們只需要繼承我們的類就可以實現快速的開發了,效果如下:



        到此處我們完成了我們的基礎開發工具的百分30的開發工作了,因為到這裡我們還需要自己去編寫我們的dao、service、controller以及mybatis配置檔案,這個過程完全是一個幹苦力的過程,因此在下一章我們將編寫一個工具類來幫我們快速生成以上的程式碼,該專案的GitHub地址:https://github.com/185594-5-27/csdndemo/tree/base-druid-swagger-tool-one

QQ交流群:578746866