基于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 文件存放到项目中,文件结构如下:

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

导入依赖

使用 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多种读文件方式

  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JSON 数据导入数据库的一般流程如下: 1. 读取 JSON 数据 2. 解析 JSON 数据为 Java 对象 3. 连接数据库 4. 将 Java 对象转换为数据库的记录 5. 插入记录到数据库 下面是一个示例代码,假设 JSON 数据格式如下: ```json [ { "id": 1, "name": "Alice", "age": 20 }, { "id": 2, "name": "Bob", "age": 25 } ] ``` Java 代码如下: ```java import java.io.FileReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.List; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class Main { public static void main(String[] args) throws Exception { // 1. 读取 JSON 数据 FileReader reader = new FileReader("data.json"); // 2. 解析 JSON 数据为 Java 对象 Gson gson = new Gson(); List<Person> persons = gson.fromJson(reader, new TypeToken<List<Person>>() {}.getType()); // 3. 连接数据库 Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456"); // 4. 将 Java 对象转换为数据库的记录 PreparedStatement stmt = conn.prepareStatement("INSERT INTO persons (id, name, age) VALUES (?, ?, ?)"); for (Person person : persons) { stmt.setInt(1, person.getId()); stmt.setString(2, person.getName()); stmt.setInt(3, person.getAge()); stmt.executeUpdate(); } // 5. 插入记录到数据库 stmt.close(); conn.close(); } } class Person { private int id; private String name; private int age; 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 getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` 这个示例代码使用了 Google Gson 库来解析 JSON 数据为 Java 对象,使用了 JDBC 来连接 MySQL 数据库。请根据自己的需求修改连接字符串、账号密码等参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值