MyBatis Plus 的 Service 更新数据
1. 简单介绍
嗨,大家好,今天给想给大家分享一下关于Mybatis-plus 的 Service 层的一些方法的使用。今天没有总结,因为都是一些API没有什么可以总结的,直接看着调用就可以了。
下边的连接也可以看到同样的内容: 这里地址就是带中文的
https://wnagzainote.yuque.com/books/share/46f28001-903f-4fb6-abdc-ecf9c2bf02bb?# 《MyBatis Plus 学习》
下面将介绍 IService 中的 update 方法,该类型的方法用来更新数据,可以根据 ID 进行单条数据更新,或者批量更新
2. 接口说明
接口提供了如下三个 save 方法:
// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根据 whereEntity 条件,更新记录
boolean update(T entity, Wrapper<T> updateWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);
3. 参数说明
- updateWrapper:实体对象封装操作类 UpdateWrapper
- entity:实体对象
- entityList:实体对象集合
- batchSize:更新批次数量
4. 实例代码
4.1 根据用户 ID 更新用户数据
import com.hxstrive.mybatis_plus.model.UserBean;
import com.hxstrive.mybatis_plus.service.UserService;
import jdk.nashorn.internal.ir.EmptyNode;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
class Update1Test {
@Autowired
private UserService userService;
@Test
void contextLoads() {
UserBean entity = new UserBean(11, "tom");
boolean flag = userService.updateById(entity);
System.out.println("flag=" + flag);
}
}
4.2 批量更新用户信息,依然根据用户ID进行更新
需要注意的是:这里的用户ID即主键
import com.hxstrive.mybatis_plus.model.UserBean;
import com.hxstrive.mybatis_plus.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
class Save2Test {
@Autowired
private UserService userService;
@Test
void contextLoads() {
List<UserBean> userBeanList = new ArrayList<>();
userBeanList.add(new UserBean(9991, "name-9991", "女", 20));
userBeanList.add(new UserBean(9992, "name-9992", "男", 30));
userBeanList.add(new UserBean(9993, "name-9993", "男", 40));
boolean flag = userService.saveBatch(userBeanList);
System.out.println("flag=" + flag);
}
}
4.3 根据 UpdateWrapper 对象构建的条件进行更新
@Test
void contextLoads() {
UpdateWrapper<UserBean> wrapper = new UpdateWrapper<>();
wrapper.ge("user_id", 11);
wrapper.le("user_id", 14);
UserBean entity = new UserBean();
entity.setName("name-" + System.currentTimeMillis());
boolean flag = userService.update(entity, wrapper);
System.out.println("flag=" + flag);
}
4.4 注意事项说明
- 请注意,这里我们所描述的一切方法都是基于 Service 层来说的
- 请注意,这里我们所描述的一切方法都是不是基于 Mapper 层来说的