前言
自己很对自己在项目中集成MongoDb做的导入导出以及模板下载的方法总结如下,有不到之处敬请批评指正!
1、pom.xml依赖引入
<!-- excel导入导出 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
</dependency>
<!--mongodb-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2、application.yml配置文件的编写
server:
port: 25021
servlet:
context-path: /dangerous
spring:
application:
name: gnhg-dangerous
datasource:
driver-class-name: dm.jdbc.driver.DmDriver
url: jdbc:dm://localhost:5236/GNHG?compatibleMode=oracle&characterEncoding=UTF-8
username: root
password: 123456
name: datasource
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 10
max-active: 100
max-wait: 600000
min-idle: 10
validation-query: SELECT 1
test-on-borrow: false
test-on-return: false
min-evictable-idle-time-millis: 300000
test-while-idle: true
time-between-eviction-runs-millis: 30000
max-pool-prepared-statement-per-connection-size: 20
pool-prepared-statements: true
max-open-prepared-statements: 20
redis:
host: localhost
port: 6379
activiti:
db-history-used: true
history-level: audit
async-executor-activate: true
main:
allow-bean-definition-overriding: true
jackson:
default-property-inclusion: non_null
data:
mongodb:
uri: mongodb://localhost/gp-gnhg
cloud:
nacos:
config:
enabled: true #nacos配置
server-addr: 127.0.0.1:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8721
ribbon:
MaxAutoRetries: 2 #最大重试次数,当注册中心中可以找到服务,但是服务连不上时将会重试,如果eureka中找不到服务则直接走断路器
MaxAutoRetriesNextServer: 3 #切换实例的重试次数
OkToRetryOnAllOperations: false #对所有操作请求都进行重试,如果是get则可以,如果是post,put等操作没有实现幂等的情况下是很危险的,所以设置为false
ConnectTimeout: 5000 #请求连接的超时时间
ReadTimeout: 6000 #请求处理的超时时间
pagehelper:
reasonable: true
support-methods-arguments: true
page-size-zero: true
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.graphsafe.api.model.dangerous.po
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
logging:
file: /gnhg_dangerous.log
pattern:
file: '%d{yyyy-MMM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{15} - %msg%n'
level:
root: info
datasource:
type: Oracle #MySQL,SQLServer,Oracle
3、EasyExcelUtil工具类的编写
package com.graphsafe.dangerous.untils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import java.io.OutputStream;
import java.util.List;
/**
* @description: easyExcel工具辅助类
* @author: songwp
* @create: 2022-01-16 14:23
**/
public class EasyExcelUtil {
public static void writeExcelWithModel(OutputStream outputStream, List<? extends Object> dataList, Class<? extends Object> classT, String sheetName, CellWriteHandler... cellWriteHandlers) {
// 头的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
// 单元格策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 初始化表格样式
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
ExcelWriterSheetBuilder excelWriterSheetBuilder = EasyExcel.write(outputStream, classT).sheet(sheetName).registerWriteHandler(horizontalCellStyleStrategy);
if (null != cellWriteHandlers && cellWriteHandlers.length > 0) {
for (int i = 0; i < cellWriteHandlers.length; i++) {
excelWriterSheetBuilder.registerWriteHandler(cellWriteHandlers[i]);
}
}
// 开始导出
excelWriterSheetBuilder.doWrite(dataList);
}
}
4、MongoDbUtil工具类的编写
package com.graphsafe.dangerous.untils;
import com.graphsafe.dangerous.model.dto.MongodbFile;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @Description: MongoDbUtil
* @auther: songwp
* @date: 2022/1/17 17:35
**/
@Component
public class MongoDbUtil {
@Autowired
private GridFsTemplate gridFsTemplate;
@Resource
private MongoDbFactory mongoDbFactory;
/**
* @Description:上传文件到mongodb返回文件id
* @Param: [file]
* @return: java.lang.String
* @Author: songwp
* @Date: 15:56
**/
public String uploadFileBackId(MultipartFile file, HttpServletRequest request){
try {
ObjectId store = gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), request.getContentType());
return store.toString();
} catch (IOException e) {
System.out.println("获取文件输入流错误。。。。。");
e.printStackTrace();
return null;
}
}
/**
* @Description:上传文件到mongodb返回文件
* @Param: [file]
* @return: java.lang.String
* @Author: songwp
* @Date: 15:56
**/
public GridFSFile uploadFileBackFile(MultipartFile file, HttpServletRequest request){
try {
ObjectId store = gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(), request.getContentType());
Query query = Query.query(Criteria.where("_id").is(store.toString()));
// 查询单个文件
GridFSFile gfsfile = gridFsTemplate.findOne(query);
return gfsfile;
} catch (IOException e) {
System.out.println("获取文件输入流错误。。。。。");
e.printStackTrace();
return null;
}
}
/**
* @Description: 根据mongodb中文件id下载文件
* @Param: [response, request, fileId]
* @return: void
* @Author: songwp
* @Date: 15:59
*/
public void downloadFile(HttpServletResponse response, HttpServletRequest request, String fileId){
try {
Query query = Query.query(Criteria.where("_id").is(fileId));
// 查询单个文件
GridFSFile gfsfile = gridFsTemplate.findOne(query);
if (gfsfile == null) {
return;
}
GridFsResource gridFsResource = new GridFsResource(gfsfile, GridFSBuckets.create(mongoDbFactory.getDb()).openDownloadStream(gfsfile.getObjectId()));
String fileName = gfsfile.getFilename().replace(",", "");
//处理中文文件名乱码
if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")
|| request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
} else {
//非IE浏览器的处理:
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}
// 通知浏览器进行文件下载
response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
IOUtils.copy(gridFsResource.getInputStream(),response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @Description: 根据mongodb中文件id获取文件的导出流数据,不让浏览器显示下载提示
* @Param: [response, fileId]
* @return: void
* @Author: songwp
* @Date: 15:14
*/
public void getDownloadOutputStream(HttpServletResponse response, String fileId){
try {
Query query = Query.query(Criteria.where("_id").is(fileId));
// 查询单个文件
GridFSFile gfsfile = gridFsTemplate.findOne(query);
if (gfsfile == null) {
return;
}
GridFsResource gridFsResource=new GridFsResource(gfsfile,GridFSBuckets.create(mongoDbFactory.getDb()).openDownloadStream(gfsfile.getObjectId()));
IOUtils.copy(gridFsResource.getInputStream(),response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void deleteByFileId(String fileId){
Query query = Query.query(Criteria.where("_id").is(fileId));
GridFSFile gfsfile = gridFsTemplate.findOne(query);
if (gfsfile == null) {
return;
}
gridFsTemplate.delete(query);
}
/**
* @Description: 根据文件id查询文件信息
* @Param: [fileId]
* @return: com.graphsafe.security.MongodbFile
* @Author: songwp
* @Date: 14:00
*/
public MongodbFile getMongodFileInfoById(String fileId){
Query query = Query.query(Criteria.where("_id").is(fileId));
GridFSFile gfsfile = gridFsTemplate.findOne(query);
if(gfsfile!=null){
String fileName = gfsfile.getFilename();
if(fileName.contains(".")){
String type = fileName.substring(fileName.lastIndexOf("."),fileName.length());
return new MongodbFile(fileId,fileName,gfsfile.getLength(),gfsfile.getUploadDate(),type);
}
}
return null;
}
/**
* @Description //TODO 法律法规录入数据用
* @Date 2022/01/16
* @Param [file2]
* @return com.graphsafe.msg.RestMessage<java.lang.String>
* @Author zwh
**/
public String uploadFileBackFileId(InputStream inputStream, String fileName) {
ObjectId objectId = gridFsTemplate.store(inputStream, fileName);
return objectId.toString();
}
/**
* @Author: songwp
* @Date: 2022/01/16 15:06
* @Description: 上传excel
* @params
* @return:
*/
public String uploadExcelBackId(File file, HttpServletRequest request){
try {
InputStream inputStream = new FileInputStream(file);
if(request!=null){
ObjectId store = gridFsTemplate.store(inputStream, file.getName(),request.getContentType());
return store.toString();
}else{
ObjectId store = gridFsTemplate.store(inputStream, file.getName(),"");
return store.toString();
}
} catch (IOException e) {
System.out.println("获取文件输入流错误。。。。。");
e.printStackTrace();
return null;
}
}
}
5、mongodb附件类的编写
package com.graphsafe.dangerous.model.dto;
import java.util.Date;
/**
* @Description: mongodb附件类
* @auther: songwp
* @date: 2022/1/17 17:41
**/
public class MongodbFile {
/**
* 文件id
*/
private String fileId;
/**
* 文件名次
*/
private String filename;
/**
* 文件大小
*/
private long length;
/**
* 文件上传时间
*/
private Date uploadDate;
/**
* 文件类型
*/
private String type;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public long getLength() {
return length;
}
public void setLength(long length) {
this.length = length;
}
public Date getUploadDate() {
return uploadDate;
}
public void setUploadDate(Date uploadDate) {
this.uploadDate = uploadDate;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public MongodbFile(String fileId, String filename, long length, Date uploadDate, String type) {
this.fileId=fileId;
this.filename = filename;
this.length = length;
this.uploadDate = uploadDate;
this.type = type;
}
}
6、ExcelListener监听类的编写
package com.graphsafe.dangerous.excelModel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.ArrayList;
import java.util.List;
/**
* @Description: ExcelListener
* @auther: songwp
* @date: 2022/1/13 14:00
**/
public class ExcelListener extends AnalysisEventListener {
private List<Object> datas = new ArrayList<>();
@Override
public void invoke(Object o, AnalysisContext analysisContext) {
if (o != null){
datas.add(o);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}
7、TitleHandler操作标题行单元格颜色的编写
package com.graphsafe.dangerous.excelModel;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import java.util.HashMap;
import java.util.List;
/**
* <pre>
* 操作标题行单元格颜色
* </pre>
*
* @author songwp
* @version 1.00.00
*
*/
@Slf4j
public class TitleHandler implements CellWriteHandler {
//操作列
private List<Integer> columnIndexs;
//颜色
private Short colorIndex;
// 批注<列的下标,批注内容>
private HashMap<Integer,String> annotationsMap;
// 下拉框值
private HashMap<Integer,String[]> dropDownMap;
public TitleHandler(List<Integer> columnIndexs, Short colorIndex, HashMap<Integer, String> annotationsMap) {
this.columnIndexs = columnIndexs;
this.colorIndex = colorIndex;
this.annotationsMap = annotationsMap;
}
public TitleHandler(List<Integer> columnIndexs, Short colorIndex) {
this.columnIndexs = columnIndexs;
this.colorIndex = colorIndex;
}
public TitleHandler(List<Integer> columnIndexs, Short colorIndex, HashMap<Integer, String> annotationsMap, HashMap<Integer, String[]> dropDownMap) {
this.columnIndexs = columnIndexs;
this.colorIndex = colorIndex;
this.annotationsMap = annotationsMap;
this.dropDownMap = dropDownMap;
}
public TitleHandler(HashMap<Integer, String[]> dropDownMap) {
this.dropDownMap = dropDownMap;
}
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
if(isHead){
// 设置列宽
Sheet sheet = writeSheetHolder.getSheet();
// sheet.setColumnWidth(cell.getColumnIndex(), 20 * 256);
writeSheetHolder.getSheet().getRow(0).setHeight((short)(1.8*256));
Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
Drawing<?> drawing = sheet.createDrawingPatriarch();
// 设置标题字体样式
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontName("宋体");
headWriteFont.setFontHeightInPoints((short)14);
headWriteFont.setBold(true);
if (CollectionUtils.isNotEmpty(columnIndexs) &&
colorIndex != null &&
columnIndexs.contains(cell.getColumnIndex())) {
// 设置字体颜色
headWriteFont.setColor(colorIndex);
}
headWriteCellStyle.setWriteFont(headWriteFont);
headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
CellStyle cellStyle = StyleUtil.buildHeadCellStyle(workbook, headWriteCellStyle);
cell.setCellStyle(cellStyle);
if (null != annotationsMap && annotationsMap.containsKey(cell.getColumnIndex())) {
// 批注内容
String context = annotationsMap.get(cell.getColumnIndex());
// 创建绘图对象
Comment comment=drawing.createCellComment(new XSSFClientAnchor(0, 0, 0,0, (short) cell.getColumnIndex(), 0, (short) 5, 5));
comment.setString(new XSSFRichTextString(context));
cell.setCellComment(comment);
}
if(null != dropDownMap &&
!dropDownMap.isEmpty() &&
dropDownMap.containsKey(cell.getColumnIndex())){
String[] datas = dropDownMap.get(cell.getColumnIndex());
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
DataValidationConstraint dvConstraint = dvHelper
.createExplicitListConstraint(datas);
CellRangeAddressList addressList = null;
DataValidation validation = null;
for (int i = 1; i < 1000; i++) {
addressList = new CellRangeAddressList(i, i, cell.getColumnIndex(), cell.getColumnIndex());
validation = dvHelper.createValidation(
dvConstraint, addressList);
sheet.addValidationData(validation);
}
}
}
}
}
8、危化品运输车辆导入、导出实体类的编写
(1)危化品运输车辆导出实体类
package com.graphsafe.dangerous.excelModel;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
import java.math.BigDecimal;
/**
* @Description: 危化品运输车辆导出实体类
* @auther: songwp
* @date: 2022/1/12 20:48
**/
@Data
public class TransportCarExportExcel {
@ExcelProperty(value = {"危化品运输车辆","序号"},index = 0)
private Integer index;
@ExcelProperty(value = {"危化品运输车辆","车牌号码"},index = 1)
private String carCode;
@ExcelProperty(value = {"危化品运输车辆","所属企业"},index = 2)
private String unitName;
@ExcelProperty(value = {"危化品运输车辆","备案企业"},index = 3)
private String enterpriseName;
@ExcelProperty(value = {"危化品运输车辆","车辆型号"},index = 4)
private String vehicleModel;
@ExcelProperty(value = {"危化品运输车辆","总重量"},index = 5)
private BigDecimal weight;
@ExcelProperty(value = {"危化品运输车辆","载重"},index = 6)
private BigDecimal capacity;
@ExcelProperty(value = {"危化品运输车辆","运输危化品名称"},index = 7)
private String chemicalsName;
}
(2)危化品运输车辆导入实体类
package com.graphsafe.dangerous.excelModel;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* @Description: 危化品运输车辆导入实体类
* @auther: songwp
* @date: 2022/1/12 20:01
**/
@Data
public class TransportCarImportExcel {
@ExcelProperty(value = {"危化品运输车辆","所属企业"},index = 0)
private String unitName;
@ExcelProperty(value = {"危化品运输车辆","备案企业"},index = 1)
private String enterpriseName;
@ExcelProperty(value = {"危化品运输车辆","车牌号码"},index = 2)
private String carCode;
@ExcelProperty(value = {"危化品运输车辆","车牌颜色"},index = 3)
private String carCodeColor;
@ExcelProperty(value = {"危化品运输车辆","运输危化品名称"},index = 4)
private String chemicalsName;
@ExcelProperty(value = {"危化品运输车辆","载重"},index = 5)
private String capacity;
@ExcelProperty(value = {"危化品运输车辆","总质量"},index = 6)
private String weight;
@ExcelProperty(value = {"危化品运输车辆","经度"},index = 7)
private String lon;
@ExcelProperty(value = {"危化品运输车辆","纬度"},index = 8)
private String lat;
@ExcelProperty(value = {"危化品运输车辆","车辆型号"},index = 9)
private String vehicleModel;
}
9、危化品运输车辆导入模板下载方法的编写
@Resource
private MongoDbUtil mongoDbUtil;
/**
* 危化品运输车辆导入模板下载
* @param request
* @return
*/
@PostMapping(value = "/templateDownload", produces = "application/json;charset=UTF-8")
public RestMessage<String> templateDownload(HttpServletRequest request) {
String backId = "";
try {
// 输出流
String fileName = "../fileStorage/危化品运输车辆导入模板.xlsx";
OutputStream outputStream = new FileOutputStream(fileName);
List<TransportCarImportExcel> dataList = new ArrayList<>();
EasyExcelUtil.writeExcelWithModel(outputStream, dataList, TransportCarImportExcel.class, "危化品运输车辆");
File file = new File(fileName);
//针对post请求,先上传到文件存储系统,返回前端再下载
backId = mongoDbUtil.uploadExcelBackId(file, request);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new RestMessage<>(backId);
}
10、危化品运输车辆信息导出
@Resource
private MongoDbUtil mongoDbUtil;
/**
* 危化品运输车辆信息导出方法的编写
* @param request
* @return
*/
@PostMapping(value = "/exportCarExcel", produces = "application/json;charset=UTF-8")
public RestMessage<String> exportCarExcel(@RequestBody BaseExampleDto baseExampleDto, HttpServletRequest request){
List<TransportCarExportExcel> list = new ArrayList<>();
// 不分页
baseExampleDto.setLimit(null);
baseExampleDto.setPage(null);
List<CpsTransportCar> rows = this.getByExample(baseExampleDto).getData().getRows();
for (int i = 0;i < rows.size();i++) {
TransportCarExportExcel exportExcel = new TransportCarExportExcel();
BeanUtils.copyProperties(rows.get(i), exportExcel);
// 序号
exportExcel.setIndex(i+1);
// 车牌号
exportExcel.setCarCode(rows.get(i).getCarCode());
// 运输企业
exportExcel.setUnitName(rows.get(i).getUnitName());
// 备案企业
exportExcel.setEnterpriseName(rows.get(i).getEnterpriseName());
// 车辆型号
exportExcel.setVehicleModel(rows.get(i).getVehicleModel());
// 总质量
exportExcel.setWeight(rows.get(i).getWeight());
// 载重
exportExcel.setCapacity(rows.get(i).getCapacity());
// 运输危化品名称
exportExcel.setChemicalsName(rows.get(i).getChemicalsName());
list.add(exportExcel);
}
String fileName = "../fileStorage/危化品运输车辆信息.xlsx";
EasyExcel.write(fileName, TransportCarExportExcel.class)
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("危化品运输车辆清单")
.doWrite(list);
File file = new File(fileName);
//针对post请求,先上传到文件存储系统,返回前端再下载
String backId = mongoDbUtil.uploadExcelBackId(file, request);
return new RestMessage<>(backId);
}
11、危化品运输车辆信息导入方法的编写
/**
* 危化品运输车辆信息导入
* @param file
* @param request
* @return
*/
@PostMapping(value = "/importExcel", produces = "application/json;charset=UTF-8")
@Transactional(rollbackFor = Exception.class)
public RestMessage importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
try {
ExcelListener excelListener = new ExcelListener();
List<TransportCarImportExcel> list = EasyExcel.read(
file.getInputStream(), TransportCarImportExcel.class, excelListener)
.sheet(0).doReadSync();
StringBuilder unitNameMessage = new StringBuilder(),
enterpriseNameMessage = new StringBuilder(),
carCodeMessage = new StringBuilder(),
carCodeColorNameMessage = new StringBuilder(),
chemicalsNameMessage = new StringBuilder(),
capacityMessage = new StringBuilder() ,
weightMessage = new StringBuilder(),
lonMessage = new StringBuilder(),
latMessage = new StringBuilder(),
vehicleModelMessage = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
if (StringUtils.isEmpty(list.get(i).getUnitName())) {
unitNameMessage.append("第" + (i + 3) + "行,所属企业名称未填写!");
return new RestMessage<>(RespCodeAndMsg.FAIL.getCode(), unitNameMessage.toString());
}
if (StringUtils.isEmpty(list.get(i).getEnterpriseName())) {
enterpriseNameMessage.append("第" + (i + 3) + "行,备案企业名称未填写!");
return new RestMessage<>(RespCodeAndMsg.FAIL.getCode(), enterpriseNameMessage.toString());
}
if (StringUtils.isEmpty(list.get(i).getCarCode())) {
carCodeMessage.append("第" + (i + 3) + "行,车牌号码未填写!");
return new RestMessage<>(RespCodeAndMsg.FAIL.getCode(), carCodeMessage.toString());
}
if (StringUtils.isEmpty(list.get(i).getCarCodeColor())) {
carCodeColorNameMessage.append("第" + (i + 3) + "行,车牌颜色未填写!");
return new RestMessage<>(RespCodeAndMsg.FAIL.getCode(), carCodeColorNameMessage.toString());
}
if (StringUtils.isEmpty(list.get(i).getChemicalsName())) {
chemicalsNameMessage.append("第" + (i + 3) + "行,运输危化品名称未填写!");
return new RestMessage<>(RespCodeAndMsg.FAIL.getCode(), chemicalsNameMessage.toString());
}
if (StringUtils.isEmpty(list.get(i).getCapacity())) {
capacityMessage.append("第" + (i + 3) + "行,载重信息未填写!");
return new RestMessage<>(RespCodeAndMsg.FAIL.getCode(), capacityMessage.toString());
}
if (StringUtils.isEmpty(list.get(i).getWeight())) {
weightMessage.append("第" + (i + 3) + "行,总重量信息未填写!");
return new RestMessage<>(RespCodeAndMsg.FAIL.getCode(), weightMessage.toString());
}
if (StringUtils.isEmpty(list.get(i).getLon())) {
lonMessage.append("第" + (i + 3) + "行,经度信息未填写!");
return new RestMessage<>(RespCodeAndMsg.FAIL.getCode(), lonMessage.toString());
}
if (StringUtils.isEmpty(list.get(i).getLat())) {
latMessage.append("第" + (i + 3) + "行,纬度信息未填写!");
return new RestMessage<>(RespCodeAndMsg.FAIL.getCode(), latMessage.toString());
}
if (StringUtils.isEmpty(list.get(i).getVehicleModel())) {
vehicleModelMessage.append("第" + (i + 3) + "行,车辆型号信息未填写!");
return new RestMessage<>(RespCodeAndMsg.FAIL.getCode(), vehicleModelMessage.toString());
}
}
for (int i = 0; i < list.size(); i++) {
CpsTransportCar transportCar = new CpsTransportCar();
//所属企业名称
transportCar.setUnitName(list.get(i).getUnitName());
//车牌号码
transportCar.setCarCode(list.get(i).getCarCode());
//车牌颜色
transportCar.setCarCodeColor(list.get(i).getCarCodeColor());
//运输危化品名称
transportCar.setEnterpriseName(list.get(i).getChemicalsName());
//载重
transportCar.setCapacity(new BigDecimal(list.get(i).getCapacity()));
//总质量
transportCar.setWeight(new BigDecimal(list.get(i).getWeight()));
//经度
transportCar.setLon(new BigDecimal(list.get(i).getLon()));
//维度
transportCar.setLat(new BigDecimal(list.get(i).getLat()));
//车辆型号
transportCar.setVehicleModel(list.get(i).getVehicleModel());
// 备案企业名称
transportCar.setEnterpriseName(list.get(i).getEnterpriseName());
cpsTransportCarService.updateOrSave(transportCar);
}
} catch (Exception e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return new RestMessage<>(RespCodeAndMsg.FAIL.getCode(), e.getMessage());
}
return new RestMessage<>(RespCodeAndMsg.SUCCESS, "导入成功");
}
12、返回值的封装方法的编写
(1)RespCodeAndMsg的编写
package com.graphsafe.api.msg;
public enum RespCodeAndMsg {
FAIL(0,"error"),
SUCCESS(1,"success");
RespCodeAndMsg(int code, String msg)
{
this.code = code;
this.msg = msg;
}
private int code;
private String msg;
public int getCode() {
return this.code;
}
public String getMsg() {
return this.msg;
}
}
(2)RespCodeAndMsg的编写
package com.graphsafe.api.msg;
public class RestMessage<T> extends BaseMessage{
T data;
public RestMessage() {
this(RespCodeAndMsg.SUCCESS);
}
public RestMessage(T data) {
super();
this.setData(data);
}
public RestMessage(RespCodeAndMsg respCodeAndMsg) {
this(respCodeAndMsg.getCode(),respCodeAndMsg.getMsg());
}
public RestMessage(RespCodeAndMsg respCodeAndMsg, T data) {
this(data,respCodeAndMsg.getCode(),respCodeAndMsg.getMsg());
}
public RestMessage(int code, String message) {
super(code,message);
}
public RestMessage(T data, int code) {
super(code);
this.setData(data);
}
/*public RestMessage(T data, String message) {
this.setMessage(message);
this.setData(data);
}*/
public RestMessage(T data, int code, String message) {
this.setCode(code);
this.setMessage(message);
this.setData(data);
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
(3)BaseMessage编写
package com.graphsafe.api.msg;
public class BaseMessage {
private int code = 1;
private String message = "success";
public BaseMessage() {
}
public BaseMessage(RespCodeAndMsg respCodeAndMsg) {
this.code = respCodeAndMsg.getCode();
this.message = respCodeAndMsg.getMsg();
}
public BaseMessage(int code) {
this.setCode(code);
}
public BaseMessage(int code, String msg) {
this.setCode(code);
this.setMessage(msg);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
注意:MongoDbUtil之前是feign接口方式写的,由于业务代码调整以我上述方法来作为示例