SpringBootMybatis批量插入Oracle数据库数据
前端数据
有如下需求,前端提交一个对象cabinData,保存到数据表中,对象结构如下:
{
"shipId":"424",
"shipName":"大唐2号",
"ballastCabinData":["艏尖舱","双层底1左","双层底1右","双层底2左","双层底2右","双层底3左","双层底3右","双层底4左","双层底4右","双层底5左","双层底5右","顶边5左","顶边5右","尾尖舱"],
"freshCabinData":["淡水舱1左","淡水舱1右"]
}
数据表结构
数据表是oracle,表结构为:
后端Controller:
@PostMapping("/savecabin")
public ajaxResult savecabin(@RequestBody Map<String,Object> postCabinData){
// 获取map中的参数
String shipIdStr = (String) postCabinData.get("shipId");
Integer shipId = Integer.valueOf(shipIdStr);
String shipName = (String) postCabinData.get("shipName");
List<String> ballastCabinData = (List<String>) postCabinData.get("ballastCabinData");
List<String> freshCabinData = (List<String>) postCabinData.get("freshCabinData");
// 获取shipid下的所有的船舱记录
List<DraftCabin> list = draftCabinService.selectCabinByShipId(shipId);
// 船舱记录大于0时,执行批量删除;船舱
if (list.size()>0){
List<Long> idcards= list.stream().map(DraftCabin::getCabinId).collect(Collectors.toList());
Long[] ids = idcards.toArray(new Long[idcards.size()]);
draftCabinService.deleteDraftCabinByIds(ids);
}
// 批量插入船舱
draftCabinService.insertDraftCabins(ballastCabinData,shipId,"压舱水",shipName);
draftCabinService.insertDraftCabins(freshCabinData,shipId,"淡水",shipName);
return AjaxResult.success();
}
解析:
- 使用
Map<String,Object>
来接收前端cabinData的JSON对象:使用map.get("shipId")方法来解析JSON获得对应的值。 - 批量删除时,使用list.stream().map(DraftCabin::getCabinId).collect(Collectors.toList())方法,使用类中的getCabinId方法来将结果集中的cabbinId形成数组参数,入参批量删除方法
deleteDraftCabinByIds
- 批量插入时,调用service的insertDraftCabins方法,传入四个参数(ballastCabinData,shipId,"压舱水",shipName)
mapper
public int insertDraftCabins(@Param("DraftCabin")List DraftCabin, @Param("shipId")Integer shipId, @Param("cabinType")String cabinType,@Param("shipName")String shipName) ;
解析:
mapper中,多个参数使用@Param注解来接收,在mybaits的xml中,调用注解名称。
xml
<!--批量新增-->
<insert id="insertDraftCabins" useGeneratedKeys="false">
INSERT ALL
<foreach collection="DraftCabin" item="item" index="index">
INTO draft_cabin
(cabin_name,ship_id,cabin_type,ship_name)
values(#{item},#{shipId},#{cabinType},#{shipName,jdbcType=VARCHAR})
</foreach>
SELECT 1 FROM DUAL
</insert>
解析:
- 批量新增
insertDraftCabins
,接收多个参数,这时不要添加parameterType属性,useGeneratedKeys="false",一定要添加; - foreach的collection是要遍历的对象,这里填写mapper中的注解名称;
orcale的批量插入方法与mysql有很大区别,这里需要注意以下:
insert all
into <tableName>[(<table_column1>,<table_column2>...)]
values([<column_value1>,<column_value2>...])
[into <tableName>[(<table_column1>,<table_column2>...)]
values([<column_value1>,<column_value2>...])]...
select <table_value1>[,<table_value2>...] from dual;
到此这篇关于SpringBoot mybatis批量插入oracle数据库数据的文章就介绍到这了,更多相关springBoot 批量插入Oracle 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关文章