SpringBoot+Mybatis+mp的CRUD操作

2022-07-29 14:38:30

一.插入操作

基于上篇文章:https://blog.csdn.net/weixin_54401017/article/details/125744429?spm=1001.2014.3001.5502

测试

   @Test
    public void TestInsert(){
        User user = new User();
        user.setName("zs");
        int i = userMapper.insert(user);

    }

注意:实体中

@TableId(type = IdType.AUTO):这个用来设置主键的增加方式,默认是自增长

@TableField

 二.更新

1.根据id更新

2.根据条件更新

三.删除

1.根据id进行删除

   @Test
    public void testDeleteById(){
        int i = userMapper.deleteById(1);
    }

2.根据map进行删除

 @Test
    public  void testDeleteByMap(){
        Map<String,Object> map = new HashMap<>();
        map.put("name","zs");
        //根据map删除数据,多条件之间是AND关系
      int i = userMapper.deleteByMap(map);
    }

3.根据QueryWrapper进行删除

 @Test
    public void testDeleteByQueryWrapper(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",1).eq("name","zs");
        //根据包装条件进行删除
        int i = userMapper.delete(queryWrapper);
    }

4.根据UpdateWrapper进行删除

    @Test
    public void testDeleteByUpdateWrapper(){
        User user = new User();
        user.setId(1);
        user.setName("zs");

        UpdateWrapper<User> UpdateWrapper = new UpdateWrapper<>(user);

        //根据包装条件删除
        int i = userMapper.delete(UpdateWrapper);
    }

5.根据ids集合进行删除

    @Test
    public void testDeleteByBatchIds(){
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);

        int i = userMapper.deleteBatchIds(list);
    }

四.查询

1.根据id进行查询

@Test
    public void testSelectById(){
        User user = userMapper.selectById(1);
    }

2.根据ids集合进行查询

 @Test
    public void testSelectByIds(){
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        List<User> userList = userMapper.selectBatchIds(list);
    }

3.根据QueryWrapper查询一条数据

@Test
    public void testSelectOne(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //查询条件
        queryWrapper.eq("name","li");

        //查询出的数据超过一条时,会抛出异常
        User user = userMapper.selectOne(queryWrapper);
    }

4.查询满足条件的数据条数

5. 查询满足条件的数据

 6.分页查询

首先需要一个配置类中配置分页插件

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.cd.mp.mapper")
public class MybatisPlusConfig {

    @Bean//设置分页插件
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }

}

  • 作者:羡云不羡君
  • 原文链接:https://blog.csdn.net/weixin_54401017/article/details/125767671
    更新时间:2022-07-29 14:38:30