A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

大家在经过一段时间的开发实际上已经积累的自己的一套的开发框架或者一些自己的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, 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.getName());
                    String value = object2json(props.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;
                        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/c ... id-swagger-tool-one


---------------------
【转载】
作者:笨_鸟_不_会_飞
原文:https://blog.csdn.net/linzhefeng89/article/details/78748919


2 个回复

倒序浏览
回复 使用道具 举报
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马