Background Import dependency implementation method Method 1 Method 2 Summary references

Since the database has only tables and no data has been filled, we plan to import the data in the Json file and insert it into the background database for development and testing. This article focuses on how to import a local Json file into a background database based on the SpringBoot project.

background

There is a table named Product in the database. The table creation information is as follows:

CREATE TABLE `product` (

  `productId` int(20NOT NULL.

  `productName` varchar(100DEFAULT NULL.

  `discontinued` varchar(10DEFAULT NULL.

  `unitsInStock` int(10DEFAULT NULL.

  `unitPrice` double(10.2NOT NULL.

  PRIMARY KEY (`productId`)

ENGINE=InnoDB DEFAULT CHARSET=utf8;

Copy the code

The definition of this table in the SpringBoot project is implemented, including implementation classes, mapper interfaces, mapping files, and Controller files.

The data about the product table is stored in a Json file in the following format:

[{

    "ProductID"1.

    "ProductName""Chai".

    "UnitPrice"18.

    "UnitsInStock"39.

    "Discontinued"false

}, {

    "ProductID"2.

    "ProductName""Chang".

    "UnitPrice"19.

    "UnitsInStock"17.

    "Discontinued"false

}, {... }

]

Copy the code

Store the JSON file in the project with the following structure:

Next we read the data and store the database.

Import dependence

Fastjson is used to convert String data to 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>

Copy the code

implementation

Methods a

Test on the annotated classes of @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(a) throws IOException {



        File jsonFile = ResourceUtils.getFile("classpath:static/data.json");

        // Data read

        String json = FileUtils.readFileToString(jsonFile);

        //String converts a String to a Json array

        JSONArray jsonArray = JSON.parseArray(json);

        // Iterate over each JSON object and store the content in the Product object

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



            // Data insertion

            mapper.save(product);

        }

    }

}

Copy the code

Way 2

Create a Service class, JsonUtilService

@Service

public class JsonUtilService {



    @Value("classpath:static/data.json")

    public Resource resource;



    public String getData(a){

        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();

    }

}

Copy the code

It is then injected into the test class.

@SpringBootTest

class SpringbootStudy05ApplicationTests {



    @Autowired

    JsonUtilService service;



    @Autowired

    ProductMapper mapper;



    @Test

    void getData(a) 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);

        }

    }

}

Copy the code

conclusion

Note: these two methods into jar package is likely to read no data. Solution: Modify the Json file reading method as follows:

public static String getFileJson(a) throws IOException {



    ClassPathResource classPathResource = new ClassPathResource("static/data.json");

    byte[]  bytes= FileCopyUtils.copyToByteArray(classPathResource.getInputStream());

    rturn new String(bytes);

}

Copy the code

reference

The SpringBoot project reads the json file configuration

Java Multiple file reading methods