【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中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

MySQL数据库双机热备的配置方法详解

《MySQL数据库双机热备的配置方法详解》在企业级应用中,数据库的高可用性和数据的安全性是至关重要的,MySQL作为最流行的开源关系型数据库管理系统之一,提供了多种方式来实现高可用性,其中双机热备(M... 目录1. 环境准备1.1 安装mysql1.2 配置MySQL1.2.1 主服务器配置1.2.2 从

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

Java中的.close()举例详解

《Java中的.close()举例详解》.close()方法只适用于通过window.open()打开的弹出窗口,对于浏览器的主窗口,如果没有得到用户允许是不能关闭的,:本文主要介绍Java中的.... 目录当你遇到以下三种情况时,一定要记得使用 .close():用法作用举例如何判断代码中的 input