基于SpringBoot将Json数据导入到数据库

简介: 基于SpringBoot将Json数据导入到数据库

由于数据库目前只有表,还未填充数据,因此计划通过导入 Json 文件中的数据,插入到后台数据库,供开发测试。本文主要讲解基于 SpringBoot 项目如何将本地 Json 文件导入到后台数据库。


背景


数据库中有一张名为 product 的表,表创建信息如下:


CREATE TABLE `product` (
  `productId` int(20) NOT NULL,
  `productName` varchar(100) DEFAULT NULL,
  `discontinued` varchar(10) DEFAULT NULL,
  `unitsInStock` int(10) DEFAULT NULL,
  `unitPrice` double(10,2) NOT NULL,
  PRIMARY KEY (`productId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
复制代码


SpringBoot 项目中关于该表的定义都已实现,包括实现类,mapper 接口,映射文件和 controller 文件。


关于 product 表的数据存放在 Json 文件中,格式如下:


[{
    "ProductID": 1,
    "ProductName": "Chai",
    "UnitPrice": 18,
    "UnitsInStock": 39,
    "Discontinued": false
}, {
    "ProductID": 2,
    "ProductName": "Chang",
    "UnitPrice": 19,
    "UnitsInStock": 17,
    "Discontinued": false
}, {.....}
]
复制代码


将 json 文件存放到项目中,文件结构如下:


1.jpg


接下来我们进行数据读取和数据库存储。


导入依赖


使用 fastjson 用于将 String 类型的数据转换为 Json。


<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.47</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
复制代码


实现方式

方式一


在 @SpringBootTest 注解修饰的类中进行测试,


import org.springframework.util.ResourceUtils;
import org.apache.commons.io.FileUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.msdn.mapper.ProductMapper;
import com.msdn.pojo.Product;
@SpringBootTest
class SpringbootStudy05ApplicationTests {
    @Autowired
    ProductMapper mapper;
    @Test
    void getData() throws IOException {
        File jsonFile = ResourceUtils.getFile("classpath:static/data.json");
        //数据读取
        String json = FileUtils.readFileToString(jsonFile);
        //String字符串转换为Json数组
        JSONArray jsonArray = JSON.parseArray(json);
        //遍历每一个json对象,将内容存放到Product对象中
        for (Object obj : jsonArray) {
            JSONObject jobj = (JSONObject) obj;
            int productId = Integer.parseInt(jobj.getString("ProductID"));
            String productName = jobj.getString("ProductName");
            String discontinued = jobj.getString("Discontinued");
            double unitPrice = Double.parseDouble(jobj.getString("UnitPrice"));
            int unitsInStock = Integer.parseInt(jobj.getString("UnitsInStock"));
            Product product = new Product();
            product.setProductId(productId);
            product.setProductName(productName);
            product.setDiscontinued(discontinued);
            product.setUnitPrice(unitPrice);
            product.setUnitsInStock(unitsInStock);
            //数据插入
            mapper.save(product);
        }
    }
}
复制代码


方式二


新建一个 Service 类 JsonUtilService


@Service
public class JsonUtilService {
    @Value("classpath:static/data.json")
    public Resource resource;
    public String getData(){
        try {
            File file = resource.getFile();
            String jsonData = this.jsonRead(file);
            return jsonData;
        } catch (Exception e) {
            return null;
        }
    }
    private String jsonRead(File file) throws IOException{
        BufferedReader reader = null;
        StringBuilder buffer = new StringBuilder();
        reader = new BufferedReader(new FileReader(file));
        String line = "";
        while ((line = reader.readLine()) != null){
            buffer.append(line);
        }
        reader.close();
        return buffer.toString();
    }
}
复制代码


然后注入到测试类中。


@SpringBootTest
class SpringbootStudy05ApplicationTests {
    @Autowired
    JsonUtilService service;
    @Autowired
    ProductMapper mapper;
    @Test
    void getData() throws IOException {
        String value = service.getData();
        JSONArray jsonArray = JSONObject.parseArray(value);
        for (Object obj : jsonArray) {
            JSONObject jobj = (JSONObject) obj;
            int productId = Integer.parseInt(jobj.getString("ProductID"));
            String productName = jobj.getString("ProductName");
            String discontinued = jobj.getString("Discontinued");
            double unitPrice = Double.parseDouble(jobj.getString("UnitPrice"));
            int unitsInStock = Integer.parseInt(jobj.getString("UnitsInStock"));
            Product product = new Product();
            product.setProductId(productId);
            product.setProductName(productName);
            product.setDiscontinued(discontinued);
            product.setUnitPrice(unitPrice);
            product.setUnitsInStock(unitsInStock);
            mapper.save(product);
        }
    }
}
复制代码


总结


注意:这两种方式打成jar包很有可能读取不到数据。解决方案:修改 Json 文件的读取方式,代码如下:


public static String getFileJson() throws IOException {
    ClassPathResource classPathResource = new ClassPathResource("static/data.json");
    byte[]  bytes= FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
    rturn new String(bytes);
}


目录
相关文章
|
8月前
|
机器学习/深度学习 JSON 监控
淘宝拍立淘按图搜索与商品详情API的JSON数据返回详解
通过调用taobao.item.get接口,获取商品标题、价格、销量、SKU、图片、属性、促销信息等全量数据。
|
7月前
|
JSON API 数据格式
淘宝拍立淘按图搜索API系列,json数据返回
淘宝拍立淘按图搜索API系列通过图像识别技术实现商品搜索功能,调用后返回的JSON数据包含商品标题、图片链接、价格、销量、相似度评分等核心字段,支持分页和详细商品信息展示。以下是该API接口返回的JSON数据示例及详细解析:
|
7月前
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
7月前
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
8月前
|
JSON 缓存 自然语言处理
多语言实时数据微店商品详情API:技术实现与JSON数据解析指南
通过以上技术实现与解析指南,开发者可高效构建支持多语言的实时商品详情系统,满足全球化电商场景需求。
|
8月前
|
JSON API 数据格式
干货满满!淘宝商品详情数据,淘宝API(json数据返回)
淘宝商品详情 API 接口(如 taobao.item.get)的 JSON 数据返回示例如下
|
7月前
|
JSON 中间件 Java
【GoGin】(3)Gin的数据渲染和中间件的使用:数据渲染、返回JSON、浅.JSON()源码、中间件、Next()方法
我们在正常注册中间件时,会打断原有的运行流程,但是你可以在中间件函数内部添加Next()方法,这样可以让原有的运行流程继续执行,当原有的运行流程结束后再回来执行中间件内部的内容。​ c.Writer.WriteHeaderNow()还会写入文本流中。可以看到使用next后,正常执行流程中并没有获得到中间件设置的值。接口还提供了一个可以修改ContentType的方法。判断了传入的状态码是否符合正确的状态码,并返回。在内部封装时,只是标注了不同的render类型。再看一下其他返回的类型;
357 3
|
7月前
|
JSON Java Go
【GoGin】(2)数据解析和绑定:结构体分析,包括JSON解析、form解析、URL解析,区分绑定的Bind方法
bind或bindXXX函数(后文中我们统一都叫bind函数)的作用就是将,以方便后续业务逻辑的处理。
449 4