Mapper中的Selective在我们编写CRUD的时候经常遇到,如insertSelective和updateByPrimaryKeySelective,顾名思义他们区别于普通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方法可以巧妙化解,具体使用还是要参照当前业务需求。