场景:两个人同时对某一变量进行修改(a=10),都想在原来基础上+10,会存在两人同时修改,最终结果还是20,正确结果应该是30。
实现:通过乐观锁实现修改
实现方式:
1,修改时把修改内容作为条件
2,加版本号
以上都需要先对数据进行查询,获取老数据的“修改内容”和版本号,以此作为修改的条件。
代码
1,实现方式通用mapper或者sql
通用mapper
OutinvEntity param = new OutinvEntity();
param.setLoadNo(outinvDetailEntity2.getLoadNo());
param.setFactoryAreaId(factoryAreaId);
param.setOrgId(orgId);
OutinvEntity resEntity = outinvMapper.selectOne(param);
if (resEntity == null) {
throw new RuntimeException("OutinvEntity is null");
}
OutinvEntity outinvEntitys = new OutinvEntity();
outinvEntitys.setLoadNo(outinvDetailEntity2.getLoadNo());
outinvEntitys.setIsPrint(OutinvIsPrintE.YES.getValue());
outinvEntitys.setStatus(OutinvStatusE.DELIVERYSTORAGE.getValue());
outinvEntitys.setShipTime(new Date());
outinvEntitys.setUpdateTime(new Date());
outinvEntitys.setUpdateUser(request.getUserName());
Example example = new Example(OutinvEntity.class);
example.createCriteria()
.andEqualTo("loadNo", outinvDetailEntity2.getLoadNo())
.andEqualTo("status", resEntity.getStatus());
int i = outinvMapper.updateByExampleSelective(outinvEntitys, example);
if (i < 1) {
throw new RuntimeException("Failed to update library status");
}
sql
<!-- 乐观锁更新 -->
<update id="updateByPrimaryKeySelectives" parameterType="com.anji.allways.business.inv.vo.OutinvVO">
update wms_outinv
<set>
<if test="status != null">
status = #{status},
</if>
<if test="shipOperator != null">
ship_operator = #{shipOperator},
</if>
<if test="shipTime != null">
ship_time = #{shipTime},
</if>
<if test="rcvMan != null">
rcv_man = #{rcvMan},
</if>
<if test="isPrint != null">
is_print = #{isPrint},
</if>
<if test="updateTime != null">
update_time = #{updateTime},
</if>
<if test="updateUser != null">
update_user = #{updateUser},
</if>
<if test="handoverTime != null">
handover_time = #{handoverTime},
</if>
<if test="handoverUser != null">
handover_user = #{handoverUser},
</if>
<if test="receiverTime != null">
receiver_time = #{receiverTime},
</if>
<if test="receiverUser != null">
receiver_user = #{receiverUser},
</if>
<if test="dueDate !=null">
due_date=#{dueDate},
</if>
</set>
<where>
<if test="id !=null">
and id = #{id}
</if>
<if test="loadNo != null">
and load_no = #{loadNo}
</if>
<if test="orgId != null">
and org_id = #{orgId}
</if>
<if test="oldDueDate !=null">
and due_date=#{oldDueDate}
</if>
<if test="status != null">
and status = #{oldStatus}
</if>
</where>
</update>
2,版本号