1.分页查询
①配置类中追加分页插件
//注册分页插件 @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }
②测试分页查询
//测试分页查询 @Test public void selectByPageTest() { Page<User> page = new Page<>(1, 3);//定义page,当前页,一页现实件数 userMapper.selectPage(page,null);//SELECT id,name,age,email,create_time,update_time,version FROM user LIMIT 0,3 page.getRecords().forEach(System.out::println);//利用page.getRecords()获取记录,并循环输出 }
2.根据id查询
//测试根据id获取数据集合 @Test public void selectIdTest() { User user = userMapper.selectById(1); System.out.println(user);//SELECT id,name,age,email,create_time,update_time,version FROM user WHERE id=? }
3.根据id批量查询
//根据id批量查询数据 @Test public void selectByBatchIDTest() { List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2));//SELECT id,name,age,email,create_time,update_time,version FROM user WHERE id IN ( ? , ? ) users.forEach(System.out::println); }
4.根据map内容进行查询
//按照map的内容查询 @Test public void selectByMapTest() { Map<String, Object> map = new HashMap<>(); map.put("name", "Tom"); userMapper.selectByMap(map).forEach(System.out::println);//SELECT id,name,age,email,create_time,update_time,version FROM user WHERE name = ? }
5.根据id删除数据
//根据id删除数据 @Test public void deleteByIdTest(){ userMapper.deleteById(1L);//DELETE FROM user WHERE id=? }
6.根据id批量删除数据
@Test public void deleteBatchByIdTest(){ userMapper.deleteBatchIds(Arrays.asList(2L,3L));//DELETE FROM user WHERE id IN ( ? , ? ) }
7.根据条件删除数据
@Test public void deleteByMapTest() { Map<String, Object> map = new HashMap<>(); map.put("name","sandy");//DELETE FROM user WHERE name = ? userMapper.deleteByMap(map); }
8.逻辑删除
物理删除:从数据库直接删除。
逻辑删除:在数据库中没有被移除,而是通过一个变量来让他失效!deleted=0 → deleted=1
①表中加上deleted字段
②实体类中追加deleted字段
@TableLogic private int deleted;
③配置类中追加逻辑删除组件
//注册逻辑删除组件 @Bean public ISqlInjector sqlInjector(){ return new LogicSqlInjector(); }
④配置文件中配置逻辑删除
#配置逻辑删除 mybatis-plus.global-config.db-config.logic-delete-value=1 mybatis-plus.global-config.db-config.logic-not-delete-value=0
⑤测试删除
@Test public void deleteLogicTest(){ userMapper.deleteById(5L);// UPDATE user SET deleted=1 WHERE id=? AND deleted=0 }
@Test public void selectLogicTest(){ userMapper.selectById(5L);//SELECT id,name,age,email,create_time,update_time,version,deleted FROM user WHERE id=? AND deleted=0 }
所有博客均为自己学习的笔记。如有错误敬请理解。