The basic data in the form of the region selection database is converted into a JSON string

  In the process of H5 development, the product manager of the basic data of the region selected some SQL from somewhere, and this data is actually difficult to change. It seems unnecessary to store it in the DB or cache in the background, so I have to find a way to It is converted into a json string and saved in a file, and the JSON string file can be directly requested when requesting.

Basic SQL:

DROP TABLE IF EXISTS Province;
DROP TABLE IF EXISTS City;
DROP TABLE IF EXISTS District;

CREATE TABLE Province (Id int,
	Name varchar(50) ,
	orderid int
)row_format=dynamic engine=innodb default charset utf8;
insert into Province values('1','北京','0');
insert into Province values('2','天津','0');

CREATE TABLE City(
	Id int ,
	ProvinceId int,
	Name varchar(50),
	AreaCode varchar(50)
)row_format=dynamic engine=innodb default charset utf8;

insert into City values('1','1','Beijing','010');
insert into City values('2','2','Tianjin','022');
insert into City values('3','3','Shijiazhuang City','0311');
insert into City values('4','3','Tangshan City','0315');

CREATE TABLE District(
	Id int ,
	CityId int ,
	Name varchar(50),
	PostCode varchar(50)
)row_format=dynamic engine=innodb default charset utf8;

insert into District values('1','1','Dongcheng','100010');
insert into District values('2','1','Xicheng District','100032');
insert into District values('3','1','Chongwen District','100061');
insert into District values('4','1','Xuanwu District','100054');
insert into District values('5','1','Chaoyang District','100020');
insert into District values('6','1','Fengtai District','100071');
insert into District values('7','1','Shijingshan','100043');

  Take a look, darling, isn't this a one-to-many relationship? So I thought of using MyBatis to deal with it. Refer to myBatis series four: query of linked data and [Mybatis advanced mapping] one-to-one mapping, one-to-many mapping, and many-to-many mapping will be written soon.

Configuration.xml

<?xml version="1.0" encoding="UTF-8"?>  
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  
<configuration>  
    <typeAliases><!-- aliases -->  
        <typeAlias alias="Province" type="com.bijian.study.dto.Province" />
        <typeAlias alias="City" type="com.bijian.study.dto.City" />
        <typeAlias alias="District" type="com.bijian.study.dto.District" />
    </typeAliases>  
      
    <environments default="development">  
      <environment id="development">  
        <transactionManager type="JDBC"/>  
        <dataSource type="POOLED"><!-- data source-->  
            <property name="driver" value="com.mysql.jdbc.Driver" />  
            <property name="url" value="jdbc:mysql://10.107.96.172:3306/test" />  
            <property name="username" value="test" />  
            <property name="password" value="test" />  
        </dataSource>  
      </environment>  
    </environments>
      
    <mappers><!-- ORM mapping file -->  
        <mapper resource="com/bijian/study/dto/Province.xml" />
        <mapper resource="com/bijian/study/dto/City.xml" />
        <mapper resource="com/bijian/study/dto/District.xml" />
    </mappers>  
</configuration>

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>  
<configuration status="OFF">  
  <appenders>  
    <Console name="Console" target="SYSTEM_OUT">  
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>  
    </Console>  
  </appenders>  
  <loggers>  
    <root level="info">  
      <appender-ref ref="Console"/>  
    </root>  
  </loggers>  
</configuration>

ProvinceMapper.java

package com.bijian.study.dao;

import java.util.List;

import com.bijian.study.dto.Province;

public interface ProvinceMapper {
    
    Province getProvinceById(int id);
    List<Province> getProvinceList();
    
    List<Province> getAllProvinceList();
}

Province.java

package com.bijian.study.dto;

import java.util.List;

public class Province {

    private int id;
    private String name;
    private int orderid;
    private List<City> subs;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getOrderid() {
        return orderid;
    }
    public void setOrderid(int orderid) {
        this.orderid = orderid;
    }
    public List<City> getSubs() {
      return subs;
    }
    public void setSubs(List<City> subs) {
      this.subs = subs;
    }
}

Province.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.bijian.study.dao.ProvinceMapper">
	
	<resultMap type="Province" id="provinceList1">
		<id column="Id" property="id" />
		<result column="Name" property="name" />
		<result column="orderid" property="orderid" />
	</resultMap>

	<select id="getProvinceById" parameterType="int" resultType="Province">
		select * from Province where Id = #{id}
	</select>

	<select id="getProvinceList" resultMap="provinceList1">
		select * from Province
	</select>
	
	<resultMap type="Province" id="provinceList">
		<result column="p_id" property="id" />
		<result column="p_name" property="name" />
		<!-- Province property maps to City class -->
		<collection property="subs" ofType="City">
			<id column="c_id" property="id" />
			<result column="c_provinceId" property="provinceId"/>
			<result column="c_name" property="name" />
			<result column="c_areaCode" property="areaCode" />
			<!-- District property maps to District class -->
			<collection property="subs" ofType="District">
				<id column="d_id" property="id" />
				<result column="d_cityId" property="cityId" />
				<result column="d_name" property="name" />
				<result column="d_postCode" property="postCode" />	
			</collection>
		</collection>
	</resultMap>

	<select id="getAllProvinceList" resultMap="provinceList">
		select p.Id p_id, p.Name p_name, c.Id c_id, c.ProvinceId c_provinceId, c.Name c_name, c.AreaCode c_areaCode, d.Id d_id, d.CityId d_cityId, d.Name d_name, d.PostCode d_postCode
		from Province p inner join City c on p.Id=c.ProvinceId
		inner join District d on c.Id=d.CityId
	</select>
</mapper>

Main.java

package com.bijian.study;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bijian.study.dao.ProvinceMapper;
import com.bijian.study.dto.Province;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    
    private static final Logger log = LoggerFactory.getLogger(Main.class);  
    private static SqlSessionFactory sqlSessionFactory;  
  
    private static Reader reader;
    
    public static void main(String[] args) {
        try {
            reader = Resources.getResourceAsReader("Configuration.xml");  
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            
            SqlSession session = sqlSessionFactory.openSession();
            
            ProvinceMapper mapper = session.getMapper(ProvinceMapper.class);  
            List<Province> provinceList = mapper.getAllProvinceList();
            log.info("{}", provinceList.size());
            
            ObjectMapper objMapper = new ObjectMapper();
            String provinceListStr = objMapper.writeValueAsString(provinceList);
            
            log.info("{}", provinceListStr);
        } catch (IOException e) {  
            log.error("Error thrown while reading the configuration: {}", e);  
        } finally {  
            if (reader != null) {  
                try {  
                    reader.close();  
                } catch (IOException e) {  
                    log.error("Error thrown while closing the reader: {}", e);  
                }  
            }  
        }  
    }
}

Running Main.java, the result is as follows:


  Of course, since in practical applications, there is no need for id, cityId, etc., postCode and areaCode also use code uniformly, so modify the corresponding sqlMapper and dto, see the attached project package "JsonTransfer.rar" for details, and the result of running Main2.java is as follows Show:

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326972236&siteId=291194637