批量添加数据
程序员文章站
2022-07-13 13:09:28
...
controller层
//批量增加
@PostMapping("/importXscBackUserExcel")
@ApiOperation(value = "(批量导入信息")//这是swagger的接口
public Result<BaseFacility> importXscBackUserExcel(@RequestParam("file") MultipartFile file) throws Exception {
return baseFacilityService.importXscBackUserExcel(file);
}
service层
//导入用户信息
@Transactional
public Result importXscBackUserExcel(MultipartFile file) {
try {
//excel列名
String[] columnNames = {"xxx", "xxx", "xxx"};
//实体类对应的字段
String[] key = {"xxx", "xxx", "xxx"};
List<JSONObject> excelList = ExcelUtils.leading(file, columnNames, key);
if(CollectionUtils.isEmpty(excelList)){
return Result.exception("表格数据为空");
}
HashMap hashMap = new HashMap();
List<BaseFacility> baseFacilityList = new ArrayList<>();
//对导入的数据进行操作
for (JSONObject excelInfo : excelList) {
//将JSON转化为实体
BaseFacility baseFacility = (BaseFacility) JSONObject.toBean(excelInfo, BaseFacility.class);
baseFacility.setCreateId(uid);
baseFacility.setUpdateId(uid);
//加入
baseFacilityList.add(baseFacility);
}
if (baseFacilityList.size() > 0) {
hashMap.put("list", baseFacilityList);
baseFacilityDao.insertBatchMessage(hashMap);
}
} catch (Exception e) {
e.printStackTrace();
return Result.exception("导入异常");
}
return Result.success();
}
dao层
//批量添加信息
void insertBatchMessage(HashMap hashMap);
xml文件
<!--NOW():获取数据库的时间 -->
<insert id="insertBatchMessage">
insert into xxx(xxx,xxx,xxxx,xxx) values
<foreach collection="list" item="item" separator=",">
(#{item.name},#{item.address},NOW()
, 0)
</foreach>
</insert>
上一篇: Struts2的基本配置-web.xml