在往sqlserver数据库新增、修改数据后,可能需要紧接着进行其他操作,比如将数据写入redis,此时需要该条数据的id作为hash结构中的key。而当sql设置主键自增时,传来的参数是不带id的,所有需要在dao层执行新增更新操作后返回主键。
dao层
- 新增操作,使用useGeneratedKeys=“true” keyProperty=“id”
<insert id="addFormula" parameterType="testmaven06calculation.com.cal.res.pojo.CalData" useGeneratedKeys="true" keyProperty="id">
insert into cal_data(formula,standard,msg)values(#{formula},#{standard},#{msg});
</insert>
- 更新操作
<update id="updateFormula" parameterType="testmaven06calculation.com.cal.res.pojo.CalData" >
<selectKey keyProperty="id" resultType="int" order="AFTER">
select id from cal_data where formula=#{formula};
</selectKey>
update cal_data set standard=#{standard},msg=#{msg} where formula=#{formula};
</update>
service层
@Transactional(rollbackFor = Exception.class)
public AjaxMessage addUpdateFormula(CalData calData) {
redisTemplate.setEnableTransactionSupport(true);
// 检查公式是否存在
if (existFormula(calData.getFormula())) { // 公式存在
// 执行更新操作
try {
redisTemplate.multi();
calDataDao.updateFormula(calData);
redisTemplate.opsForHash().put("calDataHash", String.valueOf(calData.getId()), calData);
redisTemplate.exec();
return new AjaxMessage(true, "公式已存在,更新成功", null);
} catch (Exception e) {
redisTemplate.discard();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return new AjaxMessage(false, "公式已存在,更新失败", null);
}
} else { // 公式不存在
// 执行新增操作
try {
redisTemplate.multi();
calDataDao.addFormula(calData);
redisTemplate.opsForSet().add("formulaSet", calData.getFormula());
redisTemplate.opsForHash().put("calDataHash", String.valueOf(calData.getId()), calData);
redisTemplate.exec();
return new AjaxMessage(true, "公式不存在,新增成功", null);
} catch (Exception e) {
redisTemplate.discard();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return new AjaxMessage(false, "公式不存在,新增失败", null);
}
}
}