在Control层的方法中新增一条数据到一张表,新增之后,立刻更新另外一张表的数据字段,如果新增数据操作正确运行,更新操作发生异常,会导致数据不一致,如何避免这种情况发生,具体如下。
首先在application.xml里面配置事务管理
<tx:advice id="coreTxAdviceDev" transaction-manager="mySqlTransactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="update*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="modify*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="del*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="start*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="stop*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="assign*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="clear*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="execute*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="insert*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="do*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="set*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="verify*" propagation="REQUIRED" rollback-for="Exception" />
<tx:method name="*N" propagation="NEVER" />
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
一旦Service层的方法开启事务操作的时候发生异常,立刻回滚所有的操作,这样保证数据一致。
例如Control层的代码如下:
@RequestMapping(value="/addInsTaskDangerImg",produces="application/json;charset=UTF-8")
@ResponseBody
public Feedback addInsTaskDangerImg(InsTaskDangerForm itDangerForm,Files files,HttpSession session,Model model){
LoginUser user=VisitorUtil.getUser(session);
Feedback fb=Feedback.success("添加成功!");
if(user!=null){
try{
this.insTaskDangerImageService.addEntities(itDangerForm.getId(), files);//图片添加完成,说明此任务隐患已完成
this.insTaskDangerService.updateInsTaskDangerState(itDangerForm);
//每完成一个场所检查,就check一下检查任务对应的所有场所和隐患是否都完成,若完成,更新InsTask的state
InsTaskDanger it=this.insTaskDangerService.getEntity(Integer.parseInt(itDangerForm.getId()));
long taskId=it.getTaskId();
if(this.insTaskDangerService.isAllDone(taskId)&&this.insTaskLocationService.isAllDone(taskId)){
return Feedback.success("done");
}
}catch(IOException e1){
e1.printStackTrace();
fb=Feedback.error("图片上传失败,错误位置:"+e1.getMessage());
return fb;
}catch(Exception e){
e.printStackTrace();
fb=Feedback.error("添加失败,请保证数据不为空。"+e.getMessage());
return fb;
}
return fb;
}else{
fb=Feedback.error("没有权限,请先登录!");
return fb;
}
}
代码中新增数据
this.insTaskDangerImageService.addEntities(itDangerForm.getId(), files);
之后立刻更新另外一张表的字段
this.insTaskDangerService.updateInsTaskDangerState(itDangerForm);
这两行代码应该统一写到同一个Service方法里面,一旦更新出现异常,立刻回滚操作,保证数据一致性