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

2022-12-30 09:56:20

由于数据库目前只有表,还未填充数据,因此计划通过导入 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 文件存放到项目中,文件结构如下:

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

导入依赖

使用 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);
}

参考文献

SpringBoot项目读取json格式文件配置

Java多种读文件方式

  • 作者:hresh
  • 原文链接:https://blog.csdn.net/Herishwater/article/details/106302110
    更新时间:2022-12-30 09:56:20