场景
今天写了两个接口,需要同步数据到数据库,通常是需要避免重复的,因此存在对相同数据的处理问题,一般有两种方按:
(1)根据主键信息,插入数据库时判断数据是否已经存在,如果存在则更新,不存在则插入,需要在代码里面写逻辑;
(2)通过数据库给定的特性来处理数据。
这边博文记录下第(2)中方案的实现。
技术选型
springBoot+mybatis+mysql
代码实现
1.定义接口,调用插入方法。
@PostMapping(value = "/hrDeptCostCenterRelation",
produces = "application/json; charset=UTF-8")
public String syncHRDeptCostCenterRelation(@RequestBody String data) {
try {
if (StringHelper.isBlank(data)) {
return RestConstants.MASTER_RESULT_NO_DATA_ERROR;
}
Map<String, String> dataMap = DataParseUtil.parseMasterData(data);
masterDataService.insertDeptCostCenterRelation(dataMap.get(DataParseUtil.MASTER_DATA));
} catch (Exception e) {
log.error(RestConstants.MASTER_HOTEL_NCINFO_ERROR_LOG, e);
return RestConstants.MASTER_RESULT_ERROR + e.getMessage();
}
return RestConstants.MASTER_RESULT_OK;
}
2.插入方法实现
这里使用了线程池,提高高并发下插入效率;
数据量大的情况下采用分批插入的方式。
@Autowired
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
@Override
public void insertDeptCostCenterRelation(String masterData) {
List<ThrDeptCostCenterRelation> relationList = JSONArray.parseArray(masterData,ThrDeptCostCenterRelation.class);
threadPoolTaskExecutor.execute(() -> thrDeptCostCenterRelationService.insertDeptCostCenterRelations(relationList));
}
@Override
public void insertDeptCostCenterRelations(List<ThrDeptCostCenterRelation> relationList) {
if (CollectionUtils.isEmpty(relationList)) {
return;
}
List<List<ThrDeptCostCenterRelation>> partition = Lists.partition(relationList, 100);
for (List<ThrDeptCostCenterRelation> relations : partition) {
thrDeptCostCenterRelationDao.insertDeptCostCenterRelations(relations);
}
}
3.mapper配置
<insert id="insertDeptCostCenterRelations">
REPLACE INTO t_hr_deptcostcenter_relation (
id,
structureId,
costCenterCode,
modifyDateExt,
isDeleteExt,
updateTime
)
VALUES
<foreach collection="list" item="item" separator=",">
(
#{item.id,jdbcType=INTEGER},
#{item.structureId,jdbcType=INTEGER},
#{item.costCenterCode,jdbcType=VARCHAR},
#{item.modifyDateExt,jdbcType=VARCHAR},
#{item.isDeleteExt,jdbcType=INTEGER},
NOW()
)
</foreach>
</insert>
mysql提供了REPLACE INTO的插入方式,当存在相同数据的时候会覆盖原来的数据,达到更新数据的目的。
(1)replace into 的原理:
replace into 跟 insert 功能类似,不同点在于:replace into 首先尝试插入数据到表中,如果发现表中已经有此行数据(根据主键或者唯一索引判断)则先删除此行数据,然后插入新的数据;否则没有此行数据的话,直接插入新数据。
(2)replace into的应用注意事项
1)插入数据的表必须有主键或者是唯一索引!否则的话,replace into 会直接插入数据,这将导致表中出现重复的数据。
2)如果数据库里边有这条记录,则直接修改这条记录;如果没有则,则直接插入,在有外键的情况下,对主表进行这样操作时,因为如果主表存在一条记录,被从表所用时,直接使用replace into是会报错的,这和replace into的内部原理是相关(ps.它会先删除然后再插入)。
3)正确做法是- 即先删除该条存在的数据,然后再次插入这条数据,这和外键约束相悖呢,因此只能采用update和insert这样的组合,来应对外键约束,如下:
sql_select_1='''select * from one_and_two_stars where kn_id = %d ''' %( int(one_level_id))
res_num_1= self.execute_kg(sql_select_1)
if res_num_1 > 0:
# 修改该条记录
sql_update_one_and_two_stars='''update one_and_two_stars set kn_name = %s, parent_kn_id = %s where kn_id = %s''' ("'"+str(kn_name_1)+"'", str(parent_kn_id_1), int(one_level_id))
self.execute_kg(sql_update_one_and_two_stars)
self.commit_kg()
else:
# 直接插入这条数据
sql_insert_one_and_two_stars= '''insert into one_and_two_stars(kn_id,kn_name,parent_kn_id,ctime)
values('%s','%s','%s','%s')
''' % (str(one_level_id), str(kn_name_1),str(parent_kn_id_1),str(dt))
self.execute_kg(sql_insert_one_and_two_stars)
self.commit_kg()
end。