spring mysql存储json数据_基于SpringBoot将Json数据导入到数据库

本文介绍了如何在SpringBoot应用中,通过fastjson和commons-io库将Json文件中的数据读取并插入到MySQL的product表中,提供了两种实现方式,并强调了在打包成jar时可能遇到的问题及其解决方案。
摘要由CSDN通过智能技术生成

由于数据库目前只有表,还未填充数据,因此计划通过导入 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。

com.alibaba

fastjson

1.2.47

commons-io

commons-io

2.4

实现方式

方式一

在 @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);

}

参考文献

可以使用Spring Boot中的JPA(Java Persistence API)实现将JSON数据写入MySQL数据库。JPA提供了一种简单的方式来管理对象关系映射(ORM),即将Java对象映射到关系型数据库中的表。 以下是一个简单的示例: 1. 创建一个实体类,用于映射JSON数据数据库表中的字段。 ```java @Entity @Table(name = "person") public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private Integer age; // getters and setters } ``` 2. 创建一个Spring Data JPA repository接口,用于定义CRUD操作。 ```java @Repository public interface PersonRepository extends JpaRepository<Person, Long> { } ``` 3. 在Controller中获取JSON数据,并将其转换为Person对象,然后使用PersonRepository将其保存到数据库中。 ```java @RestController @RequestMapping("/person") public class PersonController { @Autowired private PersonRepository personRepository; @PostMapping("/save") public void savePerson(@RequestBody Person person) { personRepository.save(person); } } ``` 这里假设JSON数据的格式与Person类的属性相匹配。如果不匹配,可以使用Jackson库进行转换。 另外,需要在application.properties文件中配置MySQL数据库连接信息,例如: ``` spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=myusername spring.datasource.password=mypassword spring.datasource.driver-class-name=com.mysql.jdbc.Driver ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值