java - 通用 CRUD(增、删、改、查)工具类,代码高效复用

2019-07-11 13:57:51 浏览数 (1)

PS:以下代码均出自一位帅气、阳光、友善、谦逊的同事:Abel 。嘻嘻 嘻嘻....

1. 基本 CRUD 方法实现:

代码语言:javascript复制
package com.xxx.xxx.ls.xxx.utils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import com.xxx.xxx.ls.xxx.dto.LSResultDTO;
import com.xxx.xxx.ls.xxx.model.BaseModel;
import com.xxx.xxx.ls.xxx.dto.BaseDTO;
import com.xxx.xxx.ls.xxx.dto.LSExceptionResultDTO;
import com.xxx.xxx.ls.xxx.enums.ResponseStatusEnum;
import com.xxx.xxx.ls.xxx.exceptions.InstitutionException;
import com.xxx.xxx.ls.xxx.model.BaseInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.common.util.CollectionUtils;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Slf4j
public class BaseMethodUtils {
    /**
     * 根据id查询数据
     *
     * @param id
     * @param tClass
     * @param mapper
     * @param <T>
     * @param <E>
     * @return
     */
    public static <T, E> LSResultDTO<T> queryById(String id, Class<T> tClass, Mapper<E> mapper) {
        log.info("根据id查询:{}", id);
        if (StringUtils.isBlank(id)) {
            return LSExceptionResultDTO.fail(ResponseStatusEnum.PARAMETERS_ERROR);
        }
        try {
            E e = mapper.selectByPrimaryKey(id);
            log.info("查询的信息:{}", JSON.toJSONString(e));
            T t = JSON.parseObject(JSON.toJSONString(e), tClass);
            if (t == null) {
                return LSExceptionResultDTO.fail(ResponseStatusEnum.WRONG_CONFIGURATION);
            }
            return LSResultDTO.ok(t);
        } catch (Exception e) {
            return LSExceptionResultDTO.fail(ResponseStatusEnum.EXEC_FAILURE);
        }
    }

    /**
     * 查数据列表
     *
     * @param tClass
     * @param mapper
     * @param <T>
     * @param <E>
     * @return
     */
    public static <T, E> List<T> queryAll(Class<T> tClass, Mapper<E> mapper) {
        List<E> infoList = mapper.selectAll();
        return JsonTransUtils.list2OtherList(infoList, tClass);
    }

    /**
     * 根据条件查数据列表,条件为“等于”
     *
     * @param tClass
     * @param eClass
     * @param map    封装条件
     * @param mapper
     * @param <T>
     * @param <E>
     * @return
     */
    public static <T, E> List<T> queryAll(Class<T> tClass, Class<E> eClass, ImmutableMap<String, Object> map, Mapper<E> mapper) {
        Example e = new Example(eClass);
        Example.Criteria criteria = e.createCriteria();
        map.forEach(criteria::andEqualTo);
        List<E> infoList = mapper.selectByExample(e);
        return JsonTransUtils.list2OtherList(infoList, tClass);
    }

    /**
     * 根据条件查单条数据
     *
     * @param queryModel
     * @param tClass     返回类对象
     * @param eClass     数据库映射类对象
     * @param mapper
     * @param <T>
     * @param <E>
     * @return
     */
    public static <T, E> T queryOne(BaseModel queryModel, Class<T> tClass, Class<E> eClass, Mapper<E> mapper) {
        log.info("根据条件查询一条,参数query:{}", JSON.toJSONString(queryModel));
        if (queryModel == null) {
            throw new InstitutionException(400, "请求参数有误");
        }
        E e = JSON.parseObject(JSON.toJSONString(queryModel), eClass);
        E returnInfo = null;
        try {
            returnInfo = mapper.selectOne(e);
        } catch (Exception e1) {
            throw new InstitutionException(500, "执行异常,数据库可能存在多个相同条件的数据");
        }
        if (returnInfo == null) {
            log.error("没找到该条件的配置信息");
            throw new InstitutionException(404, "该条件的配置不存在");
        }
        return JSON.parseObject(JSON.toJSONString(returnInfo), tClass);
    }

    /**
     * 根据条件查询列表
     *
     * @param queryModel
     * @param eClass     映射类对象
     * @param tClass     返回类对象
     * @param mapper
     * @param <T>
     * @param <E>
     * @return
     */
    public static <T, E> List<T> queryListByWhere(BaseModel queryModel, Class<E> eClass, Class<T> tClass, Mapper<E> mapper) {
        log.info("根据条件查询,参数AppQuery:{}", JSON.toJSONString(queryModel));
        if (queryModel == null) {
            throw new InstitutionException(400, "请求参数有误");
        }
        E e = JSON.parseObject(JSON.toJSONString(queryModel), eClass);
        List<E> infoList = mapper.select(e);
        if (CollectionUtils.isEmpty(infoList)) {
            log.error("没找到该条件的配置信息");
            throw new InstitutionException(404, "该条件的配置不存在");
        }
        return JsonTransUtils.list2OtherList(infoList, tClass);
    }

    /**
     * 保存
     *
     * @param baseDTO
     * @param eClass  映射类对象
     * @param mapper
     * @param <E>
     * @return
     */
    public static <E extends BaseInfo> String save(BaseDTO baseDTO, Class<E> eClass, Mapper<E> mapper) {
        log.info("保存DTO:{}", JSON.toJSONString(baseDTO));
        if (baseDTO == null) {
            throw new InstitutionException(400, "请求参数异常");
        }
        try {
            E e = JSON.parseObject(JSON.toJSONString(baseDTO), eClass);
            e.setGmtCreate(new Date());
            e.setGmtUpdate(new Date());
            e.setUserCreate(baseDTO.getUserCreate());
            e.setUserUpdate(baseDTO.getUserCreate());
            mapper.insert(e);
            return e.getId();
        } catch (Exception e) {
            throw new InstitutionException(500, "保存失败");
        }
    }

    /**
     * 保存,null值取数据库默认值
     *
     * @param baseDTO
     * @param eClass  映射类对象
     * @param mapper
     * @param <E>
     * @return
     */
    public static <E extends BaseInfo> String saveSelective(BaseDTO baseDTO, Class<E> eClass, Mapper<E> mapper) {
        log.info("保存DTO:{}", JSON.toJSONString(baseDTO));
        if (baseDTO == null) {
            throw new InstitutionException(400, "请求参数异常");
        }
        try {
            E e = JSON.parseObject(JSON.toJSONString(baseDTO), eClass);
            e.setGmtCreate(new Date());
            e.setGmtUpdate(new Date());
            e.setUserCreate(baseDTO.getUserCreate());
            e.setUserUpdate(baseDTO.getUserCreate());
            mapper.insertSelective(e);
            return e.getId();
        } catch (Exception e) {
            throw new InstitutionException(500, "保存失败");
        }
    }

    /**
     * 更新
     *
     * @param baseDTO
     * @param eClass
     * @param mapper
     * @param <E>
     * @return
     */
    public static <E extends BaseInfo> Integer update(BaseDTO baseDTO, Class<E> eClass, Mapper<E> mapper) {
        log.info("更新AppDTO:{}", JSON.toJSONString(baseDTO));
        if (baseDTO == null) {
            throw new InstitutionException(400, "请求参数异常");
        }
        if (StringUtils.isBlank(baseDTO.getId())) {
            throw new InstitutionException(400, "id不能为空");
        }
        try {
            E e = JSON.parseObject(JSON.toJSONString(baseDTO), eClass);
            e.setGmtUpdate(new Date());
            e.setUserUpdate(baseDTO.getUserUpdate());
            return mapper.updateByPrimaryKey(e);
        } catch (Exception e) {
            throw new InstitutionException(500, "更新失败");
        }
    }

    /**
     * 更新,null值取数据库默认值
     *
     * @param baseDTO
     * @param eClass
     * @param mapper
     * @param <E>
     * @return
     */
    public static <E extends BaseInfo> Integer updateSelective(BaseDTO baseDTO, Class<E> eClass, Mapper<E> mapper) {
        log.info("更新AppDTO:{}", JSON.toJSONString(baseDTO));
        if (baseDTO == null) {
            throw new InstitutionException(400, "请求参数异常");
        }
        if (StringUtils.isBlank(baseDTO.getId())) {
            throw new InstitutionException(400, "id不能为空");
        }
        try {
            E e = JSON.parseObject(JSON.toJSONString(baseDTO), eClass);
            e.setGmtUpdate(new Date());
            e.setUserUpdate(baseDTO.getUserUpdate());
            return mapper.updateByPrimaryKeySelective(e);
        } catch (Exception e) {
            throw new InstitutionException(500, "更新失败");
        }
    }

    /**
     * 根据id删除
     *
     * @param id
     * @param mapper
     * @param <E>
     * @return
     */
    public static <E> Integer deleteById(String id, Mapper<E> mapper) {
        log.info("删除id:{}", id);
        return mapper.deleteByPrimaryKey(id);
    }
}

2. json 转换类工具类:

代码语言:javascript复制
package com.xxx.xxx.xxx.xxx.utils;

import com.alibaba.fastjson.JSON;

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

public class JsonTransUtils{

    /**
     *  转为新列表(对象属性名要相同)
     * @param originList 原列表
     * @param tClass 新列表类对象
     * @param <T>
     * @return
     */
    public static <T> List<T> list2OtherList(List originList,Class<T> tClass){
        List<T> list = new ArrayList<>();
        for (Object info : originList) {
            T t = JSON.parseObject(JSON.toJSONString(info),tClass);
            list.add(t);
        }
        return list;
    }
}

3. sql 工具类:

代码语言:javascript复制
package com.xxx.xxx.xxx.xxx.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.Field;

@Slf4j
public class SqlUtils {

    /**
     * 封装模糊查询条件,排序条件(不排序传“”或null)
     *
     * @param t              封装查询条件类
     * @param orderByContent
     * @param <T>
     * @return
     * @throws IllegalAccessException
     */
    public static <T> Example getSelectExample(T t, String orderByContent) throws IllegalAccessException {

        Example example = new Example(t.getClass());
        Example.Criteria criteria = example.createCriteria();

        if (!StringUtils.isBlank(orderByContent)) {
            example.setOrderByClause(orderByContent);
        }

        Field[] declaredFields = t.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            if (field.get(t) != null && !"serialVersionUID".equals(field.getName())) {
                criteria.andLike(field.getName(), "%"   field.get(t).toString()   "%");
            }
        }
        return example;
    }
}

0 人点赞