软件编程
位置:首页>> 软件编程>> java编程>> mybatis-plus update更新操作的三种方式(小结)

mybatis-plus update更新操作的三种方式(小结)

作者:波神小波  发布时间:2023-10-08 14:05:08 

标签:mybatis-plus,update
目录
  • 1.@ 根据id更新

  • 2.@ 条件构造器作为参数进行更新

  • 3.@ lambda构造器

  • mybatisplus update语句为null时没有拼接上去

1.@ 根据id更新


User user = new User();
user.setUserId(1);
user.setAge(29);
userMapper.updateById(user);

2.@ 条件构造器作为参数进行更新


//把名字为rhb的用户年龄更新为18,其他属性不变
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("name","rhb");
User user = new User();
user.setAge(18);
userMapper.update(user, updateWrapper);

@ 假设只更新一个字段在使用updateWrapper 的构造器中也需要构造一个实体对象,这样比较麻烦。可以使用updateWrapper的set方法


//只更新一个属性,把名字为rhb的用户年龄更新为18,其他属性不变
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
updateWrapper.eq("name","rhb").set("age", 18);
userMapper.update(null, updateWrapper);

3.@ lambda构造器


LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
lambdaUpdateWrapper.eq(User::getName, "rhb").set(User::getAge, 18);
Integer rows = userMapper.update(null, lambdaUpdateWrapper);

mybatisplus update语句为null时没有拼接上去

我有一个设置页面,数据库就相当于是key和value的样子,当value为空的时候用updatebyId就变成了


update param where key=?

就没有set就会报语法错误

这个出现的场景是如果数据库本来改自己有值更新 null时不会有问题,当数据库也是null时更新就不会拼接set
数据库有值时update null

mybatis-plus update更新操作的三种方式(小结)

数据库也为空时的更新

mybatis-plus update更新操作的三种方式(小结)

然后查解决方案:mybatisplus为null的时候不会拼接,可配置一个策略updateStrategy = FieldStrategy.IGNORED无论是啥都会拼接 但是还是会有问题,指定下类型就可以了 最后经测试有两种方案可行


@TableField(value = "PARAMVAL",updateStrategy = FieldStrategy.IGNORED,jdbcType = JdbcType.VARCHAR)
//@TableField(value = "PARAMVAL",jdbcType = JdbcType.VARCHAR, fill = FieldFill.UPDATE)
   private String paramVal;

以上两种方案均可

来源:https://blog.csdn.net/weixin_44162337/article/details/107828366

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com