后端写法总结

一、类型转换之间的工具类

package com.hengan.citicPlatGunNew.utils;

import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @desc: 模型转化Util
 * @author: lc
 * @since: 2023/6/5
 */
public class ModelConverterUtils {
    private ModelConverterUtils(){

    }
    /**
     * 创建类的一个实例
     *
     * @param beanClass 类
     */
    public static <T> T newInstance(Class<T> beanClass) {
        try {
            return beanClass.newInstance();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 属性拷贝
     *
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyProperties(Object source, Object target) {
        if (source == null) {
            return;
        }
        BeanUtils.copyProperties(source, target);
    }

    /**
     * 对象转换
     *
     * @param source      源对象
     * @param targetClass 目标对象
     * @param <T>         目标对象class类型
     * @return 返回新的目标对象
     */
    public static <T> T convert(Object source, Class<T> targetClass) {
        if (source == null) {
            return null;
        }
        T target = newInstance(targetClass);
        copyProperties(source, target);
        return target;
    }

    /**
     * 对象List转换
     *
     * @param sources     源对象
     * @param targetClass 目标对象
     * @param <T>         目标对象class类型
     * @return 返回新的目标对象List
     */
    public static <T> List<T> convert(Collection<?> sources, Class<T> targetClass) {
        if (sources == null) {
            return null;
        }
        List<T> targets = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(sources)) {
            targets = sources.stream().map(x -> convert(x, targetClass)).collect(Collectors.toList());
        }
        return targets;
    }
}

二、跨库查询

1、在resources目录下新建一个文件constants.properties

2、内容 constants.dataSource=A,13808;

3、在java文件夹下新建config文件夹,新建类文件

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * 2024-01-11
 */
@Configuration
@ConfigurationProperties(prefix = "constants", ignoreUnknownFields = false)
@PropertySource(value = "classpath:/constants.properties")
@Data
public class ConstantsConfig {
    private String dataSource;
}

4、获取参数文件中的内容信息

@Slf4j
@Service
public class ServiceImpl implements IService {
  @Resource
    GunUseFreqMapper gunUseFreqMapper;
   @Resource
    private ConstantsConfig constantsConfig;

        @Override
    public ResponseData getUsedCount() {
        Map<String,Object> resultMap = new HashMap<>();
        try{
            List<DataSourceEx> dataSourceList =new ArrayList<>();
            Map<String,Object> map = new HashMap<>();
            map.put("date", LocalDate.now());
            map.put("isDelete", Constants.SysOptionConf.DATA_STATUS_NORMAL.getCode());
            map.put("status",Constants.SysOptionConf.OUT_STATUS.getCode());
            map.put("isEnabled",Constants.SysOptionConf.USED_CODE.getCode());
            // 数据源
            String dataSource =constantsConfig.getDataSource();
            if(dataSource !=null){
                String[] configs = dataSource.split(";");
                for(String con : configs) {
                    DataSourceEx ex = new DataSourceEx();
                    String[] cons = con.split(",");
                    ex.setDbName(cons[0]);
                    ex.setOrgId(cons[1]);
                    dataSourceList.add(ex);
                }
            }
            // 获得使用率
            List<GunUsedFreq> list = gunUseFreqMapper.getGunUsedCount(dataSourceList,map);
            // 结果不为空
            if(CollectionUtils.isNotEmpty(list)){
                int totalCount =list.stream().mapToInt(GunUsedFreq::getTotalCount).sum();
                int usedCount = list.stream().mapToInt(GunUsedFreq::getUseCount).sum();
                resultMap.put("list",list);
                // 界面按照百分比显示
                resultMap.put("usedCount",usedCount);
                resultMap.put("totalCount",totalCount);
                resultMap.put("onCount",totalCount-usedCount);
            }
            return ResponseUtil.success(resultMap);
        }catch (Exception e){
            log.error(e.toString());
            return ResponseUtil.error(ResponseEnum.SERVICE_ERR);
        }
    }


}

5、mapper文件

package com.hengan.citicPlatGunNew.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hengan.citicPlatGunNew.entity.GunUsedFreq;
import com.hengan.citicPlatGunNew.entity.ex.DataSourceEx;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

/**
 * <p>
Mapper 接口 * </p> * *
@author hengan * @since 2022-01-12 */ public interface GunUseFreqMapper extends BaseMapper<GunUsedFreq> { List<GunUsedFreq> getGunUsedCount(@Param("list")List<DataSourceEx> dataSourceList, @Param("map") Map<String,Object> map); }

6、实现接口文件

<?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.hengan.citicPlatGunNew.mapper.GunUseFreqMapper">
    <select id="getGunUsedCount" parameterType="java.util.HashMap" resultType="com.hengan.citicPlatGunNew.entity.GunUsedFreq">
        <foreach collection="list" item="item" index="index" separator="UNION" >
            select a.totalCount,b.useCount,c.usedCount,(c.usedCount/a.totalCount) gunFreq, #{item.orgId} orgId
            from
            (select count(1) totalCount from `${item.dbName}`.base_gun_info where is_delete=#{map.isDelete} and is_enabled=#{map.isEnabled}) a,
            (select count(1) useCount from `${item.dbName}`.base_gun_info b left join `${item.dbName}`.busi_gun_acess_record_real r on b.gun_code = r.gun_code
                where r.gun_status=#{map.gunStatus} and b.is_delete=#{map.isDelete} and  b.is_enabled=#{map.isEnabled} and r.take_datetime like concat(#{map.date},'%')) b,
            (select count(1) usedCount from `${item.dbName}`.base_gun_info b left join `${item.dbName}`.busi_gun_acess_record_real r on b.gun_code = r.gun_code
             where  b.is_delete=#{map.isDelete} and  b.is_enabled=#{map.isEnabled} and r.take_datetime like concat(#{map.date},'%')) c
        </foreach>
    </select>
</mapper>

 

posted @ 2024-01-31 10:48  flyComeOn  阅读(10)  评论(0编辑  收藏  举报