一、测试各种查询
还是使用之前springboot项目,使用之前的user表,创建一个UserSelectTest,用于测试查询。
代码如下:单个id,多个id,多条件查询。
更多方法查看官方文档:Mapper CRUD 接口 - Select
@SpringBootTest
public class UserSelectTest {
@Autowired
UserMapper userMapper;
/** 单个id查询 */
@Test
public void testSelectById() {
User user = userMapper.selectById(1L);
System.out.println(user);
}
/** 多个id查询 */
@Test
public void testSelectBatchIds() {
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
/** 多条件查询(使用Map) */
@Test
public void testSelectByMap() {
Map<String, Object> map = new HashMap();
map.put("id", 1);
map.put("age", 20);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
}
备注:删除操作也是和查询差不多。
二、分页查询(使用分页插件)
参考自官方文档:分页插件
1.注册bean
首先需要在之前创建的mybatis-plus配置类中,注册bean。
备注:这段代码的其他设置可以在官方文档中找到。
/** 分页插件配置 */
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
2.测试分页查询
创建一个分页对象,然后指定第几页和几条数据。
然后调用getRecords()方法即可。使用IPage接口调用和使用Page对象调用,作用差不读。不过Page对象中,方法要多一些。
/** 分页查询 */
@Test
public void testSelectPage() {
// 参数1:第几页。参数2:几条(查询第1页,三条数据)
Page<User> page = new Page<>(1, 3);
IPage<User> userIPage = userMapper.selectPage(page, null);
userIPage.getRecords().forEach(System.out::println);
}
至此,分页查询已完成。