等级-所需经验值 -总经验值 输入限定 确保数据正确性
- 需求:管理后台的一个 等级规则管理,要求输入时确保数值的正确性。
- 单纯的代码实现 (添加和修改时限定)
上代码
一.controller
/**
* 新增接口
*
* @author heyujie
* @Date 2021-01-06
*/
@RequestMapping("/addItem")
@ResponseBody
public ResponseData addItem(UsersLevelUpRuleParam usersLevelUpRuleParam) {
Boolean addRes = this.usersLevelUpRuleService.add(usersLevelUpRuleParam);
if (addRes) {
return ResponseData.success();
}
throw new RuntimeException("新增失败!数值有误");
}
/**
* 编辑接口
*
* @author heyujie
* @Date 2021-01-06
*/
@RequestMapping("/editItem")
@ResponseBody
public ResponseData editItem(UsersLevelUpRuleParam usersLevelUpRuleParam) {
Boolean update = this.usersLevelUpRuleService.update(usersLevelUpRuleParam);
if (update) {
return ResponseData.success();
}
throw new RuntimeException("更新失败!数值有误");
}
二、service
@Override
public Boolean add(UsersLevelUpRuleParam param) {
UsersLevelUpRule entity = getEntity(param);
//查询当前最大等级
Integer maxLevel = this.baseMapper.findMaxLevel(param);
//查询当前最大的需要经验值
// Integer maxNeedExp = this.baseMapper.findMaxNeedExp(param);
//查询当前最大的总经验值
Integer maxTotalExp = this.baseMapper.findMaxTotalExp(param);
entity.setLevel((maxLevel + 1));
Integer needExp = param.getNeedExp();
Integer totalExp = param.getTotalExp();
// 需要经验小于总经验 本级总经验大于最大的总经验 总经验值等于上级经验值+需求经验值
if (needExp < totalExp && totalExp > maxTotalExp && totalExp == needExp + maxTotalExp) {
this.save(entity);
return true;
}
return false;
}
@Override
public Boolean update(UsersLevelUpRuleParam param) {
UsersLevelUpRule oldEntity = getOldEntity(param);
UsersLevelUpRule newEntity = getEntity(param);
ToolUtil.copyProperties(newEntity, oldEntity);
Integer level = newEntity.getLevel();
Integer needExp = newEntity.getNeedExp();
Integer totalExp = newEntity.getTotalExp();
//查询上级总经验值
Integer lastTotalExp = this.baseMapper.findLastTotalExp(level);
//查询上级需要经验值
Integer lastNeedExp = this.baseMapper.findLastNeedExp(level);
// 需要经验大于上级需要经验 本级总经验大于上级的总经验 总经验值等于上级经验值+需求经验值
if (needExp >lastNeedExp && totalExp >lastTotalExp && totalExp == needExp + lastTotalExp){
this.updateById(newEntity);
return true;
}
return false;
}
三、mapper
<select id="findMaxLevel" resultType="Integer" >
select max(level)
from mt_users_level_up_rule where 1 = 1
</select>
<select id="findMaxNeedExp" resultType="Integer" >
select max(need_exp)
from mt_users_level_up_rule where 1 = 1
</select>
<select id="findMaxTotalExp" resultType="Integer" >
select max(total_exp)
from mt_users_level_up_rule where 1 = 1
</select>
<select id="findLastTotalExp" resultType="Integer" >
select total_exp
from mt_users_level_up_rule
where level = (#{level}-1)
</select>
<select id="findLastNeedExp" resultType="Integer" >
select need_exp
from mt_users_level_up_rule
where level = (#{level}-1)
</select>
ok 搞定