日常开发记录(一):省市区三级联动接口,可以拿来直接用!
作者:互联网
前言
最近在写一个cms管理系统和一个网站接口,其中就用到了省市区三级联动的接口,其实这个不是多难,以前学习的时候就写过,不过之前都是要么通过sql,要么通过js来写,没有完全使用java的逻辑来写过接口,这次既然写了就记录下,再小的知识也是知识,温故而知新嘛!话不多说,根据步骤直接上代码!
一、数据库建表
我使用的是mysql数据库,建表语句如下:
DROP TABLE IF EXISTS `map_code`;
CREATE TABLE `map_code` (
`id` bigint(21) unsigned NOT NULL AUTO_INCREMENT,
`pid` bigint(21) NOT NULL DEFAULT '0',
`name` varchar(50) DEFAULT NULL,
`adcode` int(11) DEFAULT NULL,
`citycode` varchar(20) DEFAULT NULL,
`level` int(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3536 DEFAULT CHARSET=utf8;
通过建表sql大家应该可以看出来,所有的数据都在一个表中,而且是通过子父id来关联的,具体的数据大家可以从来这儿获取,这里边是最新最全的全国各省市区的数据。
二、开发步骤
我是在springboot框架中写的,所以大家在springboot中可以直接拿来用,别的框架其实拿来稍做修改下也是可以使用的。
1.实体类
MapCode.java
package com.people.juvenile.map.entity;
/**
* @Auther: DELL
* @Date: 2021/3/29 12:47
* @Description:
*/
public class MapCode {
private Long id;
private Long pid;
private String name;
private Integer adcode;
private String citycode;
private Integer level;
public MapCode() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPid() {
return this.pid;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAdcode() {
return this.adcode;
}
public void setAdcode(Integer adcode) {
this.adcode = adcode;
}
public String getCitycode() {
return this.citycode;
}
public void setCitycode(String citycode) {
this.citycode = citycode;
}
public Integer getLevel() {
return this.level;
}
public void setLevel(Integer level) {
this.level = level;
}
}
MapTree.java
package com.people.juvenile.map.entity;
import java.util.ArrayList;
import java.util.List;
public class MapTree {
private Long id;
private Long pid;
private String name;
private List<MapTree> children;
public MapTree() {
}
public MapTree(Long id, Long pid, String name,List<MapTree> children) {
this.id = id;
this.pid = pid;
this.name = name;
this.children = children;
}
public MapTree(Long id, Long pid, String name) {
this.id = id;
this.pid = pid;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPid() {
return pid;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<MapTree> getChildren() {
return children;
}
public void setChildren(List<MapTree> children) {
this.children = children;
}
}
2.Controller层
MapCodeController.java
package com.people.juvenile.map.controller;
import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.people.juvenile.common.entity.RespDto;
import com.people.juvenile.map.entity.MapCode;
import com.people.juvenile.map.entity.MapTree;
import com.people.juvenile.map.entity.MapTreeNode;
import com.people.juvenile.map.service.MapCodeService;
import com.people.juvenile.school.common.constant.CommonConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* 数据api
*
* @author author
* @create 2021-03-18 14:25
*/
@RestController
@RequestMapping("/mapCode/api")
public class MapCodeController {
private static Logger logger = LoggerFactory.getLogger(MapCodeController.class);
@Autowired
MapCodeService mapCodeService;
//没有使用到redis可以删除相关代码
private Cache<String, List<MapTree>> areaTreeCache1 = CacheBuilder.newBuilder().concurrencyLevel(3)
.maximumSize(1000).expireAfterWrite(12, TimeUnit.HOURS).build();
/**
* 修改后的三级联动
* @param mapCode
* @return
*/
@RequestMapping(value = "/list")
@CrossOrigin
public RespDto<List<MapTree>> findByCondition1(MapCode mapCode) {
try {
List<MapTree> mapTrees = areaTreeCache1.getIfPresent(CommonConstants.MAP_CODE_KEY);
//todo
if (mapTrees != null && mapTrees.size() > 0) {
return RespDto.success(mapTrees);
} else {
List<MapCode> list = mapCodeService.findByCondition(mapCode);
List<MapTree> ma = new ArrayList<>();
MapTree mapTree = new MapTree();
for (MapCode map : list) {
if (map.getPid().equals(1L)) {
mapTree.setId(map.getId());
mapTree.setPid(map.getPid());
mapTree.setName(map.getName());
List<MapTree> li = new ArrayList();
MapTree map1 = new MapTree();
for (MapCode p : list) {
if(p.getPid().equals(mapTree.getId())){
map1.setId(p.getId());
map1.setPid(p.getPid());
map1.setName(p.getName());
List<MapTree> l = new ArrayList();
for(MapCode c : list){
if(c.getPid().equals(map1.getId())){
l.add(new MapTree(c.getId(),c.getPid(),c.getName()));
}
}
li.add(new MapTree(p.getId(),p.getPid(),p.getName(),l));
}
}
mapTree.setChildren(li);
ma.add(new MapTree(map.getId(),map.getPid(),map.getName(),li));
logger.info("查询到数据: {}", JSON.toJSONString(ma, true));
}
}
areaTreeCache1.put(CommonConstants.MAP_CODE_KEY,ma);
return RespDto.success(ma);
}
} catch (Exception e) {
logger.error("/mapCode/api/findByCondition 失败", e);
return RespDto.fail();
}
}
}
3.service
MapCodeService.java
package com.people.juvenile.map.service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Preconditions;
import com.people.juvenile.map.entity.MapCode;
import com.people.juvenile.school.mapper.MapCodeMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* @author author
* @create 2021-03-18 14:25
*/
@Service
public class MapCodeService {
@Autowired
MapCodeMapper mapCodeMapper;
private static Logger logger = LoggerFactory.getLogger(MapCodeService.class);
public List<MapCode> findByCondition(MapCode mapCode) {
logger.debug("mapCode findByCondition, 参数: {}", JSON.toJSONString(mapCode, true));
List<MapCode> mapCodes = mapCodeMapper.findByObject(mapCode);
logger.debug("查询结果, {}", JSON.toJSONString(mapCodes, true));
return mapCodes;
}
}
4.mapper及xml
MapCodeMapper.java
package com.people.juvenile.school.mapper;
import com.people.juvenile.common.mapper.BaseMapper;
import com.people.juvenile.map.entity.MapCode;
import java.util.List;
public interface MapCodeMapper{
List<MapCode> findByObject(MapCode mapCode);
}
MapCodeMapper.xml
<?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.people.juvenile.school.mapper.MapCodeMapper">
<resultMap id="BaseResultMap" type="com.people.juvenile.map.entity.MapCode">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="pid" jdbcType="BIGINT" property="pid" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="adcode" jdbcType="INTEGER" property="adcode" />
<result column="citycode" jdbcType="VARCHAR" property="citycode" />
<result column="level" jdbcType="INTEGER" property="level" />
</resultMap>
<sql id="Base_Column_List">
id, pid, name, adcode, citycode, level
</sql>
<select id="findByCondition" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from map_code
where id = #{id,jdbcType=BIGINT}
</select>
</mapper>
到此基本上就算写完了,最后通过postman测试接口结果如下:测试地址:http://localhost:18080/mapCode/api/list
返回数据如下,只是截取了一部分的截图
总结
其实这个并不难,而且方法也有很多种,所以大家可以根据自己的熟悉程度以及自己的实际情况来进行选择,这篇文章也是为了让大家多个选择。
标签:map,name,接口,public,联动,import,省市区,com,id 来源: https://blog.csdn.net/Lu_Dai_Ma/article/details/120675694