spring boot + spring data jpa 批量插入 + POI读取 + 文件上传

说说自己玩 spring data jpa 遇到的一个坑

spring boot升级到2.0之后,就没有下面这个方法了,如果要批量插入,还是要用1.5,给save方法传一个list,直接可以批量插入,亲测8w条数据没问题;

spring boot + spring data jpa 批量插入 + POI读取 + 文件上传_第1张图片

下面帖代码,从页面上传一个excel,读取8万行表格数据之后,插入数据库

pom.xml:


   org.springframework.boot
   spring-boot-starter-parent
   1.5.10.RELEASE
    




   
      org.springframework.boot
      spring-boot-starter-data-jpa
   
   
      org.springframework.boot
      spring-boot-starter-thymeleaf
   
   
      org.springframework.boot
      spring-boot-starter-web
   

   
      org.projectlombok
      lombok
      1.16.14
   
   
      org.springframework.boot
      spring-boot-devtools
      runtime
   
   
      org.springframework.boot
      spring-boot-starter-test
      test
   
   
      mysql
      mysql-connector-java
   

   
   
      org.apache.poi
      poi
      3.17
   
   
   
      org.apache.poi
      poi-ooxml
      3.17
   
       
           io.swagger
           swagger-annotations
           1.5.9
       
   
      io.springfox
      springfox-swagger2
      2.4.0
   
   
      io.springfox
      springfox-swagger-ui
      2.4.0
   

application.yml: 

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/data_test
    username: root
    password: root
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
  http:
      multipart:
        max-file-size: 20MB
        max-request-size: 20MB

在templates文件夹下新建一个html:

 

spring boot + spring data jpa 批量插入 + POI读取 + 文件上传_第2张图片




    upload
    
    
    





文件

 

然后是controller层:

import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;



@Controller
public class UploadController {


    @Autowired
    private ExcelService excelService;


    //跳转到上传文件的页面
    @RequestMapping(path = "/upload", method = RequestMethod.GET)
    public String goUpload() {
        //跳转到 templates 目录下的 upload.html
        return "upload";
    }

    

    @ApiOperation(value = "导入Excel表", notes = "", httpMethod = "POST")
    @RequestMapping(path = "/upload/excel",method = RequestMethod.POST)
    @ResponseBody
    public String upload(MultipartFile file) throws Exception {
        excelService.getExcel(file);

        return "上传成功";
    }

 

然后是service层:

@Service
@Slf4j
public class ExcelServiceImpl implements ExcelService {

    @Autowired
    private ExcelRepository excelRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void getExcel(MultipartFile file) throws Exception {
        List list = new ArrayList();

        //1.得到上传的表
        Workbook workbook2 = WorkbookFactory.create(file.getInputStream());
        //2、获取sheet1工作表
        Sheet sheet2 = workbook2.getSheet("sheet1");
        //获取表的总行数
        int num = sheet2.getLastRowNum();
        //总列数
        int col = sheet2.getRow(0).getLastCellNum();

      
     	//遍历excel每一行
        for (int j = 1; j < num; j++) {
            Row row1 = sheet2.getRow(j);

            //获取表中第i行,第2列的单元格
            Cell cell3 = row1.getCell(1);

            //excel表的第i行,第3列的单元格
            Cell cell4 = row1.getCell(2);
            //如果单元格中有数字或者其他格式的数据,则调用setCellType()转换为string类型
            Cell cell7 = row1.getCell(4);
            cell7.setCellType(CellType.STRING);
      		//这里new 一个对象,用来装填从页面上传的Excel数据,字段根据上传的excel决定
            Excel excel= new Excel();
            
		    excel.setName(cell3.getStringCellValue());
			excel.setAge(cell4.getStringCellValue()); 
			excel.setAddress(cell7.getStringCellValue());        
			list.add(command);
        } 
		excelRepository.save(list);//批量插入数据 
    }

然后是Repository:

@Repository
public interface ExcelRepository extends CrudRepository {

}

这里的repository不需要写任何方法,默认继承了CrudRepository就有了jpa的增删改查的方法,具体用法可以查官网的api

这里注意CrudRepository 表示要用该方法对Excel实体类做增删改查

 

下面是实体类:

@Entity
@Table(name = "excel_test")
@Data
public class Excel {
    
    @Id
    @GeneratedValue
    private Integer id;
    
    @Column
    private String name;
    
    @Column
    private String age;
    
    @Column
    private String address;
    
}

 

用了上面这些注解之后,服务启动,spring jpa就会在数据库生成相应的表,然后跑起来

访问:localhost:8080/upload  ,上传一个8w条的带有name,age,address字段的excel表,就会批量插入到数据库了

你可能感兴趣的:(spring,boot,spring,data,jpa,POI)