All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.zodiac.mybatisplus.base.BaseServiceImpl Maven / Gradle / Ivy

There is a newer version: 1.6.8
Show newest version
package org.zodiac.mybatisplus.base;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotEmpty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.zodiac.commons.util.BeanUtil;
import org.zodiac.commons.util.Classes;
import org.zodiac.commons.util.Colls;
import org.zodiac.commons.util.DateTimes;
import org.zodiac.commons.util.Func;
import org.zodiac.commons.util.ObjectUtil;
import org.zodiac.commons.util.lang.Strings;
import org.zodiac.mybatisplus.binding.Binder;
import org.zodiac.mybatisplus.binding.cache.BindingCacheManager;
import org.zodiac.mybatisplus.binding.helper.ServiceAdaptor;
import org.zodiac.mybatisplus.binding.parser.PropInfo;
import org.zodiac.mybatisplus.binding.query.dynamic.DynamicJoinQueryWrapper;
import org.zodiac.mybatisplus.config.MyBatisPlusConfigInfo;
import org.zodiac.mybatisplus.constants.MyBatisPlusConstants;
import org.zodiac.mybatisplus.model.MyBatisPlusPagination;
import org.zodiac.mybatisplus.util.MyBatisPlusSpringBootUtil;
import org.zodiac.sdk.toolkit.model.KeyValue;
import org.zodiac.sdk.toolkit.util.ExceptionUtil;
import org.zodiac.sdk.toolkit.util.ReflectionUtil;
import org.zodiac.sdk.toolkit.util.lang.ObjUtil;
import org.zodiac.sdk.toolkit.util.lang.StrUtil;
import org.zodiac.security.auth.model.SecurityPlatformUser;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.ChainWrappers;

@Validated
public abstract class BaseServiceImpl, T extends BaseEntity> extends ServiceImpl implements BaseService {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    private MyBatisPlusConfigInfo myBatisPlusConfig;

    public BaseServiceImpl() {
        myBatisPlusConfig = new MyBatisPlusConfigInfo();
    }

    public BaseServiceImpl(MyBatisPlusConfigInfo myBatisPlusConfig) {
        this.myBatisPlusConfig = myBatisPlusConfig;
    }

    public final BaseServiceImpl setMyBatisPlusConfig(MyBatisPlusConfigInfo myBatisPlusConfig) {
        this.myBatisPlusConfig = myBatisPlusConfig;
        return this;
    }

    @Override
    public QueryChainWrapper query() {
        return ChainWrappers.queryChain(this.getBaseMapper());
    }

    @Override
    public LambdaQueryChainWrapper lambdaQuery() {
        return ChainWrappers.lambdaQueryChain(this.getBaseMapper());
    }

    @Override
    public UpdateChainWrapper update() {
        return ChainWrappers.updateChain(this.getBaseMapper());
    }

    @Override
    public LambdaUpdateChainWrapper lambdaUpdate() {
        return ChainWrappers.lambdaUpdateChain(this.getBaseMapper());
    }

    @Override
    public boolean saveOrUpdate(T entity) {
        if (entity.getId() == null) {
            logger.info("Id is null, save entity {}.", entity);
            return this.save(entity);
        } else {
            logger.info("Id is not null, update entity {} by id.", entity);
            return this.updateById(entity);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteLogic(@NotEmpty List ids) {
        SecurityPlatformUser user = obtainSecurityPlatformUser();
        List list = Colls.list();
        ids.forEach(id -> {
            T entity = BeanUtil.newInstance(currentModelClass());
            if (user != null) {
                entity.setUpdateUser(user.getUserId());
            }
            entity.setUpdateTime(new Date());
            entity.setId(id);
            list.add(entity);
        });
        return super.updateBatchById(list) && super.removeByIds(ids);
    }

    @Override
    public boolean changeStatus(@NotEmpty List ids, Integer status) {
        SecurityPlatformUser user = obtainSecurityPlatformUser();
        List list = Colls.list();
        ids.forEach(id -> {
            T entity = BeanUtil.newInstance(currentModelClass());
            if (user != null) {
                entity.setUpdateUser(user.getUserId());
            }
            entity.setUpdateTime(new Date());
            entity.setId(id);
            entity.setStatus(status);
            list.add(entity);
        });
        return super.updateBatchById(list);
    }

    @Override
    public boolean saveBatch(Collection entityList, int batchSize) {
        entityList.forEach(this::resolveEntity);
        return super.saveBatch(entityList, batchSize);
    }

    @Override
    public boolean saveOrUpdateBatch(Collection entityList, int batchSize) {
        entityList.forEach(this::resolveEntity);
        return super.saveOrUpdateBatch(entityList, batchSize);
    }

    @Override
    public boolean updateBatchById(Collection entityList, int batchSize) {
        entityList.forEach(this::resolveEntity);
        return super.updateBatchById(entityList, batchSize);
    }

    @Override
    public List getEntityList(Wrapper queryWrapper) {
        return getEntityList(queryWrapper, null);
    }

    @Override
    public List getEntityList(Wrapper queryWrapper, MyBatisPlusPagination myBatisPlusPagination) {
        /*如果是动态join,则调用JoinsBinder。*/
        if(queryWrapper instanceof DynamicJoinQueryWrapper){
            return Binder.joinQueryList((DynamicJoinQueryWrapper)queryWrapper, entityClass, myBatisPlusPagination);
        } else if(queryWrapper instanceof QueryWrapper) {
            QueryWrapper mpQueryWrapper = ((QueryWrapper)queryWrapper);
            if(mpQueryWrapper.getEntityClass() == null) {
                mpQueryWrapper.setEntityClass(entityClass);
            }
        } else if(queryWrapper instanceof LambdaQueryWrapper) {
            LambdaQueryWrapper mpQueryWrapper = ((LambdaQueryWrapper)queryWrapper);
            if(mpQueryWrapper.getEntityClass() == null) {
                mpQueryWrapper.setEntityClass(entityClass);
            }
        }
        /*否则,调用MP默认实现。*/
        if(myBatisPlusPagination != null){
            IPage page = convertToIPage(queryWrapper, myBatisPlusPagination);
            page = super.page(page, queryWrapper);
            /*如果重新执行了count进行查询,则更新pagination中的总数*/
//            if(page.searchCount()){
//                pagination.setTotalCount(page.getTotal());
//            }
            myBatisPlusPagination.setTotalCount(page.getTotal());
            return page.getRecords();
        } else{
            List list = super.list(queryWrapper);
            if(list == null){
                list = Collections.emptyList();
            } else if(list.size() > MyBatisPlusSpringBootUtil.getBatchSize()){
                logger.warn("单次查询记录数量过大,请及时检查优化。返回结果数={}", list.size());
            }
            return list;
        }
    }

    @Override
    public List getEntityListLimit(Wrapper queryWrapper, int limitCount) {
        /*如果是动态join,则调用JoinsBinder。*/
        if(queryWrapper instanceof DynamicJoinQueryWrapper){
            MyBatisPlusPagination myBatisPlusPagination = new MyBatisPlusPagination();
            myBatisPlusPagination.setPageIndex(1).setPageSize(limitCount);
            return Binder.joinQueryList((DynamicJoinQueryWrapper)queryWrapper, entityClass, myBatisPlusPagination);
        }
        Page page = new Page<>(1, limitCount);
        page.setSearchCount(false);
        page = super.page(page, queryWrapper);
        return page.getRecords();
    }

    @Override
    public T getSingleEntity(Wrapper queryWrapper) {
        /*如果是动态join,则调用JoinsBinder。*/
        if(queryWrapper instanceof DynamicJoinQueryWrapper){
            return (T)Binder.joinQueryOne((DynamicJoinQueryWrapper)queryWrapper, entityClass);
        }
        List entityList = getEntityListLimit(queryWrapper, 1);
        if(Colls.notEmptyColl(entityList)){
            return entityList.get(0);
        }
        return null;
    }

    @Override
    public List> getMapList(Wrapper queryWrapper, MyBatisPlusPagination myBatisPlusPagination) {
        if(myBatisPlusPagination != null){
            IPage page = convertToIPage(queryWrapper, myBatisPlusPagination);
            IPage> resultPage = super.pageMaps(page, queryWrapper);
            /*如果重新执行了count进行查询,则更新pagination中的总数*/
//            if(page.searchCount()){
//                pagination.setTotalCount(page.getTotal());
//            }
            myBatisPlusPagination.setTotalCount(page.getTotal());
            return resultPage.getRecords();
        } else{
            List> list = super.listMaps(queryWrapper);
            if(list == null){
                list = Collections.emptyList();
            } else if(list.size() > MyBatisPlusSpringBootUtil.getBatchSize()){
                logger.warn("单次查询记录数量过大,请及时检查优化。返回结果数={}", list.size());
            }
            return list;
        }
    }

    @Override
    public List getLabelValueList(Wrapper queryWrapper) {
        String sqlSelect = queryWrapper.getSqlSelect();
        /*最多支持3个属性:label, value, ext。*/
        if(StrUtil.isBlank(sqlSelect) || StrUtil.count(sqlSelect, Strings.COMMA) > 2) {
            log.error("调用错误: getLabelValueList必须用select依次指定返回的Label,Value, ext键值字段,如: new QueryWrapper().lambda().select(Dictionary::getItemName, Dictionary::getItemValue)");
            return Collections.emptyList();
        }
        List entityList = getEntityList(queryWrapper);
        if(entityList == null){
            return Collections.emptyList();
        } else if(entityList.size() > getMyBatisPlusConfig().getJoinBatchSize()) {
            logger.warn("单次查询记录数量过大,建议您及时检查优化。返回结果数={}", entityList.size());
        }
        /*转换为KeyValue。*/
        String[] selectArray = sqlSelect.split(Strings.COMMA);
        /*是否有ext字段。*/
        boolean hasExt = selectArray.length > 2;
        List labelValueList = Colls.list(entityList.size());
        for(T entity : entityList){
            PropInfo propInfo = BindingCacheManager.getPropInfoByClass(entityClass);
            String label = propInfo.getFieldByColumn(selectArray[0]), value = propInfo.getFieldByColumn(selectArray[1]), ext;
            Object labelVal = BeanUtil.getProperty(entity, label);
            Object valueVal = BeanUtil.getProperty(entity, value);
            /*如果key和value的的值都为null的时候map也为空,则不处理此项。*/
            if (ObjUtil.isEmptyObject(labelVal) && ObjUtil.isEmptyObject(valueVal)) {
                continue;
            }
            /*兼容oracle大写。*/
            KeyValue labelValue = new KeyValue(StrUtil.stringValueOf(labelVal), valueVal);
            /*设置ext。*/
            if (hasExt) {
                ext = propInfo.getFieldByColumn(selectArray[2]);
                labelValue.setExt(BeanUtil.getProperty(entity, ext));
            }
            labelValueList.add(labelValue);
        }
        return labelValueList;
    }

    protected final MyBatisPlusConfigInfo getMyBatisPlusConfig() {
        return myBatisPlusConfig;
    }

    protected Page convertToIPage(Wrapper queryWrapper, MyBatisPlusPagination myBatisPlusPagination){
        return ServiceAdaptor.convertToIPage(myBatisPlusPagination, entityClass);
    }

    protected final void resolveEntity(T entity) {
        SecurityPlatformUser user = obtainSecurityPlatformUser();
        Date now = new Date();
        if (entity.getId() == null) {
            /*处理新增逻辑。*/
            logger.info("Id is null, save entity {}.", entity);
            if (user != null) {
                logger.info("SecurityPlatformUser {} is not null.", user);
                entity.setCreateUser(user.getUserId());
                entity.setCreateDept(Func.firstLong(user.getDeptId()));
                entity.setUpdateUser(user.getUserId());
            }
            if (entity.getStatus() == null) {
                entity.setStatus(MyBatisPlusConstants.DB_STATUS_NORMAL);
            }
            entity.setCreateTime(now);
        } else if (user != null) {
            /*处理修改逻辑。*/
            logger.info("Id is not null, update entity {} by user.", entity);
            entity.setUpdateUser(user.getUserId());
        }
        /*处理通用逻辑。*/
        logger.info("Update entity {} by time {}.", DateTimes.formatDateTime(now));
        entity.setUpdateTime(now);
        entity.setIsDeleted(MyBatisPlusConstants.DB_NOT_DELETED);
        /*处理多租户逻辑,若字段值为空,则不进行操作。*/
        Field field = ReflectionUtil.getField(entity.getClass(), MyBatisPlusConstants.DB_TENANT_KEY);
        if (ObjUtil.isNotEmptyObject(field)) {
            Method getTenantId = Classes.getMethod(entity.getClass(), MyBatisPlusConstants.DB_TENANT_KEY_GET_METHOD);
            String tenantId = null;
            try {
                tenantId = String.valueOf(getTenantId.invoke(entity));
                if (ObjectUtil.isEmpty(tenantId)) {
                    Method setTenantId =
                        Classes.getMethod(entity.getClass(), MyBatisPlusConstants.DB_TENANT_KEY_SET_METHOD, String.class);
                    setTenantId.invoke(entity, (Object)null);
                    logger.info("Update entity {} by tenantId {}.", tenantId);
                }
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                logger.error("{}", ExceptionUtil.stackTrace(e));
            }
        }
    }

    protected abstract SecurityPlatformUser obtainSecurityPlatformUser();

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy