CURD操作
上一篇笔记已经讲到在整合了MP的 Spring Boot 中如何去插入数据,接下来我们继续学习CURD中的更新、删除、查询三个操作。
更新操作
我们在 test 包下测试更新,代码如下:
// 测试更新
@Test
public void testUpdate(){
User user = new User();
// 此处 将主键策略改成 INPUT 手动输入
user.setId(6L);
user.setName("关注Levin!");
user.setAge(3);
// 注意:updateById 参数是一个对象
int i = userMapper.updateById(user);
System.out.println(user);
}
查询操作
查询单个用户
需求:查询Id为1的用户
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
批量查询
需求:查询id分别为1、2、3的用户信息
用List容器接收User对象,用useMapper中的方法selectBatchIds(Arrays.asList(1,2,3))
// 测试查询 批量查询
@Test
public void testSelectByBatchId(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
使用map进行条件查询
map.put()的两个参数,一个为 字段,一个为 字段值。
// 条件查询之一 使用 map
@Test
public void testSelectByBatchIds(){
HashMap<String, Object> map = new HashMap<>();
// 自定义查询
map.put("name", "Levin");
map.put("age", 3);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
分页查询
分页在网站使用非常多,基本分为以下三类:
1、原始的 limit
进行分页
2、pageHelper 第三方插件
3、MP 其实内置分页插件
MP 内置分页插实现分页查询
1、配置拦截器组件
创建Config配置类,将下列代码加入到配置类中,配置类上要标注上@Configuration代表其为配置类,能够在IOC容器中查询到。
// 分页插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor2() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
}
2、直接使用Page对象
Page<>()的两个参数分别为 当前页 页面大小。
// 测试分页查询
@Test
public void testPage(){
// 参数一:当前页
// 参数二:页面大小
Page<User> page = new Page<>(2, 4);
userMapper.selectPage(page, null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());
}
删除操作
删除单个用户信息
需求:删除Id为1448810082501476357的用户信息。
// 测试删除
@Test
public void testDeleteById(){
userMapper.deleteById(1448810082501476357L);
}
批量删除
需求:删除Id为1448810082501476354和Id为1448810082501476355 的用户信息
// 通过id批量删除
@Test
public void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1448810082501476354L, 1448810082501476355L));
}
通过map删除
需求:通过Map删除id为1448810082501476353的用户信息
// 通过map 删除
@Test
public void testDeleteBatchId2(){
HashMap<String, Object> map = new HashMap<>();
// 先通过map.put()进行查询
map.put("Id", 1448810082501476353L);
// 删除
userMapper.deleteByMap(map);
}