【201】Java8读取JSON树形结构并插入到MySQL数据库表中

2024-04-07 14:12

本文主要是介绍【201】Java8读取JSON树形结构并插入到MySQL数据库表中,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

我写了一个 maven 项目的 Demo,用来演示 JAVA8 如何读取 JSON 文件树形结构,并将这种树形结构保存到 MySQL 中。

json文件 city.json

{"name": "山东省","sub": [{"name": "青岛市","sub": [{"name": "市南区"},{"name": "市北区"},{"name": "城阳区"},{"name": "李沧区"},]},{"name": "济南市","sub": [{"name": "市中区"},{"name": "历下区"},{"name": "天桥区"}]},{"name": "淄博市","sub": [{"name": "张店区"},{"name": "临淄区"},]},{"name": "枣庄市"},]
}

MySQL 数据库的 city 表结构:

CREATE TABLE `city` (`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '主键',`parent_id` int(10) NOT NULL COMMENT '父级ID',`name` varchar(50) NOT NULL COMMENT '名称',`del_flag` tinyint(1) NOT NULL COMMENT '0=未删除,1=已删除',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4

pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>zhangchao</groupId><artifactId>Java8Json</artifactId><version>1.0-SNAPSHOT</version><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.10.1</version>   </dependency><!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j --><dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><version>8.3.0</version></dependency><!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.15</version></dependency></dependencies>
</project>

mybatis 配置文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/><property name="username" value="root"/><property name="password" value="123456"/></dataSource></environment></environments><mappers><mapper resource="mapper/CityMapper.xml"/></mappers>
</configuration>

读取配置文件的类 DBFactory.java

package zhangchao.common.db;import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;
import java.io.InputStream;public class DBFactory {private static SqlSessionFactory sqlSessionFactory = null;static {String resource = "mybatis-config.xml";InputStream inputStream = null;try {inputStream = Resources.getResourceAsStream(resource);} catch (IOException e) {e.printStackTrace();}sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);}public static SqlSessionFactory getInstance(){return sqlSessionFactory;}}

mybatis 的 mapper XML 文件 CityMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="zhangchao.addjsontree.CityMapper"><resultMap id="rm" type="zhangchao.addjsontree.City"><id property="id" column="c_id"/><result property="parentId" column="parent_id"/><result property="name" column="name"/><result property="delFlag" column="del_flag"/></resultMap><insert id="insert" useGeneratedKeys="true" keyProperty="id">INSERT INTO `test`.`city` (parent_id,`name`,del_flag)VALUES(#{parentId},#{name},#{delFlag})</insert>
</mapper>

和数据库表对应的实体类 City.java

package zhangchao.addjsontree;public class City {private Integer id;private Integer parentId;private String name;private Integer delFlag;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public Integer getParentId() {return parentId;}public void setParentId(Integer parentId) {this.parentId = parentId;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getDelFlag() {return delFlag;}public void setDelFlag(Integer delFlag) {this.delFlag = delFlag;}
}

和 JSON 对应的 DTO 文件 CityDto.java

package zhangchao.addjsontree;import java.util.List;public class CityDto {private Integer id;private Integer parentId;private String name;private List<CityDto> sub;@Overridepublic String toString() {final StringBuffer sb = new StringBuffer("CityDto{");sb.append("id=").append(id);sb.append(", parentId=").append(parentId);sb.append(", name='").append(name).append('\'');sb.append(", sub=").append(sub);sb.append('}');return sb.toString();}public List<CityDto> getSub() {return sub;}public void setSub(List<CityDto> sub) {this.sub = sub;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public Integer getParentId() {return parentId;}public void setParentId(Integer parentId) {this.parentId = parentId;}public String getName() {return name;}public void setName(String name) {this.name = name;}}

CityMapper.java

package zhangchao.addjsontree;public interface CityMapper{int insert(City city);
}

整个程序的主方法,演示了具体插入数据库的算法。

先调用 getJSon() 方法,从 JSON 文件中获取 JSON 字符串,然后通过 GSON 转换成 CityDto 对象。

然后使用了树的宽度优先算法遍历树形结构,currentLevel 列表保存当前层节点,nextLevel 列表保存下一层节点。

每次循环把当前层节点插入数据库,并且在插入数据库后,获取数据库 ID(这里把表主键设置成整数自增)。对子节点做是否为空的检查,并且把 NULL 子节点删除掉。把数据库 ID 保存到子节点的 parentId 成员变量中。

把非空子节点加入到 nextLevel 列表中,然后让 currentLevel 引用指向 nextLevel。

package zhangchao.addjsontree;import com.google.gson.Gson;
import org.apache.ibatis.session.SqlSession;
import zhangchao.common.db.DBFactory;import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;/*** @author zhangchao */
public class TestAddJsonTree {private static String getJSon(){File f = new File("E:\\ws\\zc\\Java8Json\\src\\main\\resources\\JsonFile\\city.json");StringBuilder sb = new StringBuilder();FileInputStream fis = null;BufferedReader br = null;try {fis = new FileInputStream(f);br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));String str = br.readLine();while(str != null) {sb.append(str);str = br.readLine();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (fis != null) {fis.close();}if (br != null) {br.close();}} catch (IOException e) {e.printStackTrace();}}String json = sb.toString();return json;}private static void dtoToDomain(CityDto dto, City domain) {domain.setName(dto.getName());domain.setParentId(dto.getParentId());domain.setDelFlag(0);}public static void main(String[] args) {String json = getJSon();Gson gson = new Gson();CityDto cityDto = gson.fromJson(json, CityDto.class);if (cityDto == null) {return;}cityDto.setParentId(-1);List<CityDto> currentLevel = new ArrayList<>();currentLevel.add(cityDto);SqlSession sqlSession = DBFactory.getInstance().openSession(false);try {CityMapper cityMapper = sqlSession.getMapper(CityMapper.class);while (currentLevel != null && !currentLevel.isEmpty()) {List<CityDto> nextLevel = new ArrayList<>();for (CityDto dto : currentLevel) {City domain = new City();dtoToDomain(dto, domain);cityMapper.insert(domain);List<CityDto> sub = dto.getSub();if (sub != null && !sub.isEmpty()) {for (Iterator<CityDto> iterator = sub.iterator(); iterator.hasNext();) {CityDto item = iterator.next();if (item == null) {iterator.remove();} else {item.setParentId(domain.getId());}}nextLevel.addAll(sub);}}currentLevel = nextLevel;}sqlSession.commit();} catch (Exception e) {e.printStackTrace();sqlSession.rollback();} finally {sqlSession.close();}}
}

最后插入数据库的效果如下:

在这里插入图片描述

这篇关于【201】Java8读取JSON树形结构并插入到MySQL数据库表中的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/882813

相关文章

Java如何从Redis中批量读取数据

《Java如何从Redis中批量读取数据》:本文主要介绍Java如何从Redis中批量读取数据的情况,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一.背景概述二.分析与实现三.发现问题与屡次改进3.1.QPS过高而且波动很大3.2.程序中断,抛异常3.3.内存消

Mybatis嵌套子查询动态SQL编写实践

《Mybatis嵌套子查询动态SQL编写实践》:本文主要介绍Mybatis嵌套子查询动态SQL编写方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言一、实体类1、主类2、子类二、Mapper三、XML四、详解总结前言MyBATis的xml文件编写动态SQL

SpringBoot使用ffmpeg实现视频压缩

《SpringBoot使用ffmpeg实现视频压缩》FFmpeg是一个开源的跨平台多媒体处理工具集,用于录制,转换,编辑和流式传输音频和视频,本文将使用ffmpeg实现视频压缩功能,有需要的可以参考... 目录核心功能1.格式转换2.编解码3.音视频处理4.流媒体支持5.滤镜(Filter)安装配置linu

解决mysql插入数据锁等待超时报错:Lock wait timeout exceeded;try restarting transaction

《解决mysql插入数据锁等待超时报错:Lockwaittimeoutexceeded;tryrestartingtransaction》:本文主要介绍解决mysql插入数据锁等待超时报... 目录报错信息解决办法1、数据库中执行如下sql2、再到 INNODB_TRX 事务表中查看总结报错信息Lock

MySQL启动报错:InnoDB表空间丢失问题及解决方法

《MySQL启动报错:InnoDB表空间丢失问题及解决方法》在启动MySQL时,遇到了InnoDB:Tablespace5975wasnotfound,该错误表明MySQL在启动过程中无法找到指定的s... 目录mysql 启动报错:InnoDB 表空间丢失问题及解决方法错误分析解决方案1. 启用 inno

在Spring Boot中实现HTTPS加密通信及常见问题排查

《在SpringBoot中实现HTTPS加密通信及常见问题排查》HTTPS是HTTP的安全版本,通过SSL/TLS协议为通讯提供加密、身份验证和数据完整性保护,下面通过本文给大家介绍在SpringB... 目录一、HTTPS核心原理1.加密流程概述2.加密技术组合二、证书体系详解1、证书类型对比2. 证书获

Druid连接池实现自定义数据库密码加解密功能

《Druid连接池实现自定义数据库密码加解密功能》在现代应用开发中,数据安全是至关重要的,本文将介绍如何在​​Druid​​连接池中实现自定义的数据库密码加解密功能,有需要的小伙伴可以参考一下... 目录1. 环境准备2. 密码加密算法的选择3. 自定义 ​​DruidDataSource​​ 的密码解密3

MySQL 安装配置超完整教程

《MySQL安装配置超完整教程》MySQL是一款广泛使用的开源关系型数据库管理系统(RDBMS),由瑞典MySQLAB公司开发,目前属于Oracle公司旗下产品,:本文主要介绍MySQL安装配置... 目录一、mysql 简介二、下载 MySQL三、安装 MySQL四、配置环境变量五、配置 MySQL5.1

MySQL 添加索引5种方式示例详解(实用sql代码)

《MySQL添加索引5种方式示例详解(实用sql代码)》在MySQL数据库中添加索引可以帮助提高查询性能,尤其是在数据量大的表中,下面给大家分享MySQL添加索引5种方式示例详解(实用sql代码),... 在mysql数据库中添加索引可以帮助提高查询性能,尤其是在数据量大的表中。索引可以在创建表时定义,也可

Maven项目中集成数据库文档生成工具的操作步骤

《Maven项目中集成数据库文档生成工具的操作步骤》在Maven项目中,可以通过集成数据库文档生成工具来自动生成数据库文档,本文为大家整理了使用screw-maven-plugin(推荐)的完... 目录1. 添加插件配置到 pom.XML2. 配置数据库信息3. 执行生成命令4. 高级配置选项5. 注意事