三级分层查询省市区数据

1、数据库数据

*

2、实现的效果

3、controller层

java 复制代码
@Api(tags = "地址库")
@RestController
@RequestMapping("/basic/city")
public class DataTChinaCityController extends BaseController {

    @Resource
    private IProductSaleDeliveryService productSaleDeliveryService;

    /**
     * 查询地址库-三级联动
     */
    @GetMapping(value = "/queryCity")
    public AjaxResult queryCity() {
        return AjaxResult.success(productSaleDeliveryService.cacheChinaCityDataWhereLevel());
    }
}

4、Service层

bash 复制代码
public interface IProductSaleDeliveryService {

    /**
     * 缓存,查询地址库-三级联动
     *
     * @return 全国城市数据
     */
    Collection<BaseDataTChinaCity> cacheChinaCityDataWhereLevel();

}

5、实现层

bash 复制代码
@Service
public class ProductSaleDeliveryServiceImpl implements IProductSaleDeliveryService {

// 配合guava缓存一起使用,依赖自己搜素添加即可
// 创建缓存
    Cache<String, Object> chinaCityDataCache = Caffeine.newBuilder()
            .expireAfterAccess(2, TimeUnit.HOURS) // 访问后过期时间 2小时
            .initialCapacity(64) // 设置初始容量
            .maximumSize(128) // 设置缓存的最大容量
            .build();

@Resource
    public IBaseDataTChinaCityService baseDataTChinaCityService;

/**
     * 缓存,查询地址库-三级联动
     *
     * @return 全国城市数据
     */
    @Override
    public Collection<BaseDataTChinaCity> cacheChinaCityDataWhereLevel() {
        try {
            // 设置redis的key
            String redisKey = "juepeiscm:basedata:china:city:leveldata";

            if (chinaCityDataCache.getIfPresent(redisKey) != null) {
                return (Collection<BaseDataTChinaCity>) chinaCityDataCache.getIfPresent(redisKey);
            }
            // 三级联动
            Collection<BaseDataTChinaCity> baseDataTChinaCityCollections = baseDataTChinaCityService.queryCity();
            // 放入缓存
            chinaCityDataCache.put(redisKey, baseDataTChinaCityCollections);
            return baseDataTChinaCityCollections;
        } catch (Exception e) {
            log.error("服务产品小程序获取全国城市数据失败=", e);
        }
        return null;
    }
}

6、地址库对象 t_china_city

bash 复制代码
@ApiModel(description ="地址库")
@Data
public class BaseDataTChinaCity extends BaseEntity {
    private static final long serialVersionUID = 1L;

    /**
     * id
     */
    @ApiModelProperty(value = "id")
    private Long indexId;

    @ApiModelProperty(value = "ids")
    private List<Long> indexIds;

    @ApiModelProperty(value = "城市名称")
    @Excel(name = "城市名称")
    private String cityName;

    /**
     * 父级ID
     */
    @ApiModelProperty(value = "父级ID")
    @Excel(name = "父级ID")
    private Long parentId;

    @ApiModelProperty(value = "父级IDs")
    private List<Long> parentIds;

    /**
     * 层级
     */
    @ApiModelProperty(value = "层级")
    @Excel(name = "层级")
    private Integer addressLevel;

    /**
     * 省
     */
    @ApiModelProperty(value = "省")
    @Excel(name = "省")
    private String province;

    /**
     * 市
     */
    @ApiModelProperty(value = "市")
    @Excel(name = "市")
    private String city;

    /**
     * 区
     */
    @ApiModelProperty(value = "区")
    @Excel(name = "区")
    private String district;

    /**
     * 区域
     */
    @ApiModelProperty(value = "区域")
    @Excel(name = "区域")
    private String area;


    /**
     * 0:启用  1:作废
     */
    @ApiModelProperty(value = "0:启用  1:作废")
    @Excel(name = "0:启用  1:作废")
    private Integer status;

    @ApiModelProperty(value = "子级")
    List<BaseDataTChinaCity> children;

    @ApiModelProperty(value = "城市名称")
    String label;
    @ApiModelProperty(value = "城市名称")
    String value;

    public String getLabel() {
        return cityName;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public String getValue() {
        return cityName;
    }

    public void setValue(String value) {
        this.value = value;
    }





    @ApiModelProperty(value = "bms推送状态(0:未推送,1:推送成功,2:推送失败)")
    private Integer bmsSendStatus;

    @ApiModelProperty(value = "bms推送次数")
    private Integer bmsSendNum;

    @ApiModelProperty(value = "bms最后推送时间")
    private Date bmsLastSendTime;

}

7、地址库Service接口

bash 复制代码
public interface IBaseDataTChinaCityService {
/**
     * 查询地址库-三级联动(不带参数)
     */
    Collection<BaseDataTChinaCity> queryCity();
}

8、查询地址库-三级联动(不带参)

java 复制代码
@Service
public class BaseDataTChinaCityServiceImpl implements IBaseDataTChinaCityService {

 @Autowired
    private BaseDataTChinaCityMapper baseDataTChinaCityMapper;


/**
     * 查询地址库-三级联动(不带参)
     *
     * @return 结果
     */
    @Override
    public Collection<BaseDataTChinaCity> queryCity() {
        return queryCityByEntity(null);
    }
}

/**
     * 查询地址库-三级联动(方法提取)
     *
     * @return 结果
     */
    public Collection<BaseDataTChinaCity> queryCityByEntity(BaseDataTChinaCity baseDataTChinaCity) {
        //查询所有城市
        List<BaseDataTChinaCity> provinceList = baseDataTChinaCityMapper.queryCity(baseDataTChinaCity);
        return getCityByEntity(provinceList);
    }

public Collection<BaseDataTChinaCity> getCityByEntity(List<BaseDataTChinaCity> provinceList){
        Map<Long, BaseDataTChinaCity> oneLevel = new HashMap<>();
        Map<Long, List<BaseDataTChinaCity>> twoLevel = new HashMap<>();
        Map<Long, List<BaseDataTChinaCity>> threeLevel = new HashMap<>();
        for (BaseDataTChinaCity city : provinceList) {
            switch (city.getAddressLevel()) {
                case 1:
                    oneLevel.put(city.getIndexId(), city);
                    break;
                case 2:
                    twoLevel.computeIfAbsent(city.getParentId(), k -> new ArrayList<>());
                    twoLevel.get(city.getParentId()).add(city);
                    break;
                case 3:
                    threeLevel.computeIfAbsent(city.getParentId(), k -> new ArrayList<>());
                    threeLevel.get(city.getParentId()).add(city);
                    break;
                default:
                    break;
            }
        }
        for (Map.Entry<Long, List<BaseDataTChinaCity>> tmp :
                twoLevel.entrySet()) {
            for (BaseDataTChinaCity parentEntity :
                    tmp.getValue()) {
                parentEntity.setChildren(threeLevel.get(parentEntity.getIndexId()));
            }
        }
        for (Map.Entry<Long, BaseDataTChinaCity> tmp :
                oneLevel.entrySet()) {
            BaseDataTChinaCity parent = tmp.getValue();
            parent.setChildren(twoLevel.get(parent.getIndexId()));
        }
        return oneLevel.values();
    }

9、地址库Mapper接口

java 复制代码
@Mapper
public interface BaseDataTChinaCityMapper {
/**
     * 查询地址库-三级联动
     *
     * @param baseDataTChinaCity 地址库
     * @return 结果
     */
    List<BaseDataTChinaCity> queryCity(BaseDataTChinaCity baseDataTChinaCity);

}

<select id="queryCity" parameterType="BaseDataTChinaCity" resultMap="BaseDataTChinaCityResult">
        <include refid="selectTChinaCityVo"/>
        <where>
            <if test="parentId != null ">and parent_id = #{parentId}</if>
            <if test="addressLevel != null ">and address_level = #{addressLevel}</if>
            <if test="province != null  and province != ''">and province = #{province}</if>
            <if test="city != null  and city != ''">and city = #{city}</if>
            <if test="district != null  and district != ''">and district = #{district}</if>
            <if test="area != null  and area != ''">and area = #{area}</if>
            <if test="status != null ">and status = #{status}</if>
            <if test="bmsSendStatus != null">and bms_send_status = #{bmsSendStatus}</if>
            <if test="indexId != null">and index_id = #{indexId}</if>
            <if test="indexIds != null and indexIds.size() > 0">
                and index_id in
                <foreach collection="indexIds" item="item" separator="," open="(" close=")">
                    #{item}
                </foreach>
            </if>
            <if test="parentIds != null and parentIds.size() > 0">
                and parent_id in
                <foreach collection="parentIds" item="item" separator="," open="(" close=")">
                    #{item}
                </foreach>
            </if>
        </where>
    </select>

<sql id="selectTChinaCityVo">
        select index_id, parent_id, address_level, province, city, district, status,city_name,area from t_china_city
    </sql>

<resultMap type="BaseDataTChinaCity" id="BaseDataTChinaCityResult">
        <result property="indexId" column="index_id"/>
        <result property="cityName" column="city_name"/>
        <result property="parentId" column="parent_id"/>
        <result property="addressLevel" column="address_level"/>
        <result property="province" column="province"/>
        <result property="city" column="city"/>
        <result property="district" column="district"/>
        <result property="area" column="area"/>
        <result property="status" column="status"/>
    </resultMap>

学费了吗?有问题请留言!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

相关推荐
哦虎!1 小时前
【JavaEE】网络初识
java
for_ever_love__1 小时前
MySQL ORDER BY 排序优化:从 Using filesort 到索引有序扫描(含双路 / 单路排序原理)
java·mysql·优化·存储·by·order·filesort
我是人✓2 小时前
Java文件上传三方式对比:从传统到SpringBoot
java·开发语言
欣栀♡2 小时前
JVM 频繁 Full GC 先看日志括号里的 cause,jstat 的 FGC 在 JDK 8 上会骗人
java·jvm
IT研究室3 小时前
最新计算机毕业设计选题推荐-基于spring boot的葡萄酒文化宣传网站-网站-文档指导-Java-springboot
java·spring boot·课程设计
慧都小项3 小时前
MyEclipse 中创建和测试 JAX-RS REST 接口:从项目配置到 REST Explorer
java·restful·myeclipse·jax-rs
Wang's Blog3 小时前
Java 项目实战: 交友项目 - 入门案例:编写 Dubbo 服务提供者
java·dubbo·交友
秋饼3 小时前
Spring AI 2.0 结构化输出企业级实战:从 BeanOutputConverter 源码到生产级解析容错
java·ai·技术分享·后端开发
摇滚侠3 小时前
《计算机是如何工作的:人人都能懂的计算机软硬件工作原理》第 9 章 机器码与汇编语言 阅读笔记 9
java·开发语言·笔记
Cc.Y3 小时前
Java零基础入门:深入Java核心:文件IO与序列化全解
java·开发语言·python