美文网首页
封装service层

封装service层

作者: 吕小凯 | 来源:发表于2019-12-09 17:22 被阅读0次
package com.github.wxiaoqi.security.common.biz;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

import javax.persistence.Column;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.wxiaoqi.security.common.entity.QueryParam;
import com.github.wxiaoqi.security.common.msg.TableResultResponse;
import com.github.wxiaoqi.security.common.util.EntityUtils;
import com.github.wxiaoqi.security.common.util.Query;
import com.github.wxiaoqi.security.common.util.ReflectionUtils;
import com.github.wxiaoqi.security.common.vo.FrontUser;
import com.nimble.expense.annotation.FuzzyColumn;
import com.nimble.expense.biz.AdminUserBiz;
import com.nimble.expense.util.ReflectUtil;
import com.nimble.expense.util.SpringContextUtil;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

/**
 * Created by Mr.AG Date: 17/1/13 Time: 15:13 Version 1.0.0
 */
/* @Slf4j */
@SuppressWarnings("unchecked")
@Slf4j
public abstract class BaseBiz<M extends Mapper<T>, T> {
    @Autowired
    protected M mapper;

    public void setMapper(M mapper) {
        this.mapper = mapper;
    }

    public T selectOne(T entity) {
        return mapper.selectOne(entity);
    }

    public T selectById(Object id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<T> selectList(T entity) {
        return mapper.select(entity);
    }

    public List<T> selectListAll() {
        return mapper.selectAll();
    }

    public Long selectCount(T entity) {
        return new Long(mapper.selectCount(entity));
    }

    public void insert(T entity) {
        EntityUtils.setCreatAndUpdatInfo(entity);
        mapper.insert(entity);
    }

    public void saveOrUpdate(T entity) {
        String field = "id";
        boolean isNewRecord = true;
        if (ReflectionUtils.hasField(entity, field)) {
            Object id = ReflectUtil.getObjectFieldValueByName(entity, field);
            if(id!=null&&!id.toString().equals("")) {
                T db = this.selectById(id);
                if(db!=null) {
                    isNewRecord = false;
                }
            }
        }
        if (isNewRecord) {
            EntityUtils.setCreatAndUpdatInfo(entity);
            mapper.insert(entity);
        }
    }

    public void insertSelective(T entity) {
        EntityUtils.setCreatAndUpdatInfo(entity);
        mapper.insertSelective(entity);
    }

    public void delete(T entity) {
        mapper.delete(entity);
    }

    public void deleteById(Object id) {
        mapper.deleteByPrimaryKey(id);
    }

    public void updateById(T entity) {
        EntityUtils.setUpdatedInfo(entity);
        mapper.updateByPrimaryKey(entity);
    }

    public void updateSelectiveById(T entity) {
        EntityUtils.setUpdatedInfo(entity);
        mapper.updateByPrimaryKeySelective(entity);
    }

    /**
     * 先从数据库取出旧数据,再更新参数中存在的字段到数据库(忽略null值更新到数据库中)
     * 
     * @param entity
     */
    public void updateExistColumnById(T entity) {
        String id = ReflectUtil.getObjectIdValue(entity);
        T dbObj = this.selectById(id);
        // 忽略空值的复制
        BeanUtil.copyProperties(entity, dbObj, false,
                CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        EntityUtils.setUpdatedInfo(dbObj);
        mapper.updateByPrimaryKeySelective(entity);
    }

    public List<T> selectByExample(Object example) {
        return mapper.selectByExample(example);
    }

    public int selectCountByExample(Object example) {
        return mapper.selectCountByExample(example);
    }

    public TableResultResponse<T> selectByQuery(Query query) {

        Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        Example example = new Example(clazz);
        if (query.entrySet().size() > 0) {
            Example.Criteria criteria = example.createCriteria();
            for (Map.Entry<String, Object> entry : query.entrySet()) {
                try {
                    QueryParam param = JSONObject.parseObject(entry.getValue().toString(), QueryParam.class);
                    if (param.getQueryType() == QueryParam.QueryType.equal) {
                        criteria.andEqualTo(entry.getKey(), param.getValue());
                    } else if (param.getQueryType() == QueryParam.QueryType.not_equal) {
                        criteria.andNotEqualTo(entry.getKey(), param.getValue());
                    } else if (param.getQueryType() == QueryParam.QueryType.like) {
                        criteria.andLike(entry.getKey(), "%" + param.getValue() + "%");
                    } else if (param.getQueryType() == QueryParam.QueryType.like_before) {
                        criteria.andLike(entry.getKey(), "%" + param.getValue());
                    } else if (param.getQueryType() == QueryParam.QueryType.like_after) {
                        criteria.andLike(entry.getKey(), param.getValue() + "%");
                    } else if (param.getQueryType() == QueryParam.QueryType.not_like) {
                        criteria.andNotLike(entry.getKey(), "%" + param.getValue() + "%");
                    } else if (param.getQueryType() == QueryParam.QueryType.not_like_before) {
                        criteria.andNotLike(entry.getKey(), "%" + param.getValue());
                    } else if (param.getQueryType() == QueryParam.QueryType.not_like_after) {
                        criteria.andNotLike(entry.getKey(), param.getValue() + "%");
                    }

                } catch (Exception e) {

                    criteria.andLike(entry.getKey(), "%" + entry.getValue().toString() + "%");
                }
            }
        }
        Page<Object> result = PageHelper.startPage(query.getPage(), query.getLimit());
        List<T> list = mapper.selectByExample(example);

        try {
            Method method = clazz.getMethod("setRownum", int.class);
//          log.debug("query.getPage : {} , query.getLimit : {} ",query.getPage(), query.getLimit());
            for (int i = 0; i < list.size(); i++) {
                T t = list.get(i);
                method.invoke(t, (query.getPage() - 1 >= 0 ? query.getPage() - 1 : 0) * query.getLimit() + i + 1);
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
//          log.debug(clazz.getName() + "have not setRownum method!");
        }

        return new TableResultResponse<T>(result.getTotal(), list);
    }

    /**
     * 获取当前登陆用户
     * 
     * @return
     */
    public FrontUser getLoginUser() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        FrontUser user = null;
        if (request != null) {
            AdminUserBiz userBiz = SpringContextUtil.getBean(AdminUserBiz.class);
            user = userBiz.getLoginUser(request);
        }
        return user;
    }

    /**
     * 单个模糊搜索
     * 
     * @param fuzzyValue
     * @param columnName
     * @return
     * @throws Exception
     */
    public List<T> selectListByFuzzyKey(String fuzzyValue) throws Exception {
        if (StringUtils.isEmpty(fuzzyValue)) {
            return mapper.selectAll();
        } else {
            Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
                    .getActualTypeArguments()[1];
            Example example = new Example(clazz);

            Field[] fields = clazz.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                fields[i].setAccessible(true);
                FuzzyColumn fuzzyColumn = fields[i].getAnnotation(FuzzyColumn.class);
                Column dbColumn = fields[i].getAnnotation(Column.class);
                if (fuzzyColumn != null && dbColumn != null) {
                    String dbCloumnName = dbColumn.name();
                    example.or().andLike(dbCloumnName, "%" + fuzzyValue + "%");
                }
            }
            return mapper.selectByExample(example);
        }
    }
}

相关文章

网友评论

      本文标题:封装service层

      本文链接:https://www.haomeiwen.com/subject/ppbggctx.html