Mybatis-plus3.0 更新字段為 null


Mybatis-plus3.0 更新字段為 null

在3.0之前如果想更新數據庫的字段為 null 值,大多通過實體類上添加注解實現 ,存在一定的風險,亦或者手動寫 sql 。在 3.0 + 后提供了UpdateWrapper`更新條件構造器來實現字段置 null 值、空字符串的操作。

1、創建更新條件構造器

在這里我要置 age 的值為 null。

//第一種:new對象,字段多時使用
User user = new User();
user.setName("test");
UpdateWrapper<User> wrapper = new UpdateWrapper<>();
wrapper.set("age", null).eq("id",1294183513728778246L);

//第二種,直接在構造器上更新字段及拼接條件
UpdateWrapper<User> wrapper = new UpdateWrapper<>();
wrapper.set("age", null).set("name", "test").eq("id",1294183513728778246L)

2、使用並打印結果

通過mapper.update()方法使用構造器。

//第一種
int count =  userMapper.update(user,wrapper);

//第二種
int count =  userMapper.update(null,wrapper);

輸出結果如下

image-20201217151143513

可以看到 age 的值成功置為 null 了。

3、注意點

如果要更新 id的值,只能通過構造器上 set更新字段實現。

即通過 UpdateWrapper()set()方法。

user.setName("test");
wrapper.set("age", null).set("id",1294183513728778246L).eq("id",1)

輸出結果如下

image-20201217152416529

通過 new 對象 set Id 無效

user.setName("test");
//set Id 無效
user.setId(1294183513728778246L);
wrapper.set("age", null).eq("id",1);

輸出結果如下

image-20201217152848464


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM