MyBatis 新增更新返回主键

在往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);
			}
		}
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值