【Mybatis】Mybatis中的Selective(附例子)

    Mapper中的Selective在我们编写CRUD的时候经常遇到,如insertSelectiveupdateByPrimaryKeySelective,顾名思义他们区别于普通insert和update方法于Selective(选择性)。

updateByPrimaryKeySelective与updateByPrimaryKey的区别

    当使用updateByPrimaryKeySelective时,他会忽略你注入的值中为null的数据,只更改不为null的值。

    而当使用updateByPrimaryKey会更改全部注入的数据,若注入中有null值,也会用null覆盖掉原来的值。

以SQL语句为例:

我们要在user_info表中更改一个user对象(有id主键,username,password三个字段),若我们只设置了username字段,password为null,使用如下:

update user_info set username = 'user1' where id = 1;//updateByPrimaryKeySelective
update user_info set username = 'user1' , password = null where id = 1;//updateByPrimaryKey

insert和insertSelectivede的区别

以SQL语句为例:

我们要在user_info表中新增一个user对象(有id,username,password三个字段),若我们只设置了id主键还有username两个字段,password为null,使用如下:

insert into user_info (id,name) value (1,"user1");//insertSelective
insert into user_info (id,name) value (1,"user1", null);//insert

    所以,当遇到覆盖问题时使用selective的mapper方法可以巧妙化解,具体使用还是要参照当前业务需求。 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值