一
MybatisPlus
****.在使用mybatisplus之前,先让他继承BaseMapper
@Repository
public interface UserMapper extends BaseMapper {
}
1.查询所有
//查询所有
@Test
public void test1(){
List list = userMapper.selectList(null);
System.out.println(list);
}
2.添加
//添加
@Test
public void addUser(){
User user=new User();
user.setName(“嗷嗷嗷”);
user.setAge(12);
user.setEmail(“12@qq.com”);
int insert = userMapper.insert(user);
}
3.修改
//修改操作
@Test
public void update(){
User user=new User();
user.setId(1442763851731881986L);
user.setAge(53);
int i = userMapper.updateById(user);
System.out.println(i);
}
4.测试乐观锁
使用乐观锁之前,加上乐观锁插件
//乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
//测试乐观锁
@Test
public void testOptimistic(){
//查询
User user = userMapper.selectById(1443104406189985793L);
System.out.println(user);
//修改操作
user.setAge(99);
userMapper.updateById(user);
}
5.多个id批量查询
//多个id批量查询
@Test
public void testIds(){
Long a[]={1L,2L,3L};
List users = userMapper.selectBatchIds(Arrays.asList(a));
users.forEach(System.out::println);
}
6.通过Map条件查询
//通过mp条件查询数据
@Test
public void testMap(){
HashMap<String,Object> hashMap=new HashMap<String,Object>();
hashMap.put(“name”,“哈231”);
hashMap.put(“age”,“12”);
List list = userMapper.selectByMap(hashMap);
//迭代器的写法,输出更快,
list.forEach(System.out::println);
}
7.分页查询
首先要引入分页插件
@Bean
//分页插件
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
//分页
@Test
public void testPage(){
//创建page对象
//传入两个参数,当前页和每页显示记录数
Page page=new Page(1,5);
//调用mp分页查询方法
//把所有数据封装到page对象里
userMapper.selectPage(page,null);
//通过page对象获取分页数据
System.out.println(page.getCurrent());//当前页
System.out.println(page.getRecords());//每页数据
System.out.println(page.getSize()); //每页显示数据记录数
System.out.println(page.getTotal());//总记录数
System.out.println(page.getPages());//总页数
}
8.在mybatisplus中删除,有物理删除和逻辑删除,物理删除数据不在了,逻辑删除数据还在,但是查询的时候数据还是没有的,但是数据还是在数据库里面,并没有删除,只是被删除的字段被改为被删除状态,之后仍然可以在数据库查询
//物理删除
@Test
//物理删除
public void testDelete(){
int i = userMapper.deleteById(5L);
System.out.println(i);
}
//逻辑删除
@Bean
//逻辑删除插件
public ISqlInjector iSqlInjector(){
return new LogicSqlInjector();
}
实体类添加注解
@TableLogic
private Integer deleted;
//逻辑删除
@Test
//逻辑删除
public void testDelete(){
int i = userMapper.deleteById(1443125755201576961L);
System.out.println(i);
}
deleted为1代表已删除,数据库数据还在
9.查询的时候,mybatisplus默认会给我们查询deleted数据,配置了逻辑删除的插件和属性的注解,默认加上where deleted=0查询
物理删除:是实际删除
逻辑删除:标记为删除,数据没删除