package com.zhy.mybatisplus_project;

import com.zhy.mapper.UserMapper;
import com.zhy.pojo.User;


import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@SpringBootTest
public class MyBatisPlusTest {
    //这里爆红的原因是ioc容器中只能存在类所对应的bean,不能存在接口所对应的
    //bean,所以编译阶段会报错,运行阶段没有问题
    //可以选择加上required = false,或者在mapper层的接口加上@repository注解
    @Autowired(required = false)
    UserMapper userMapper;
    

    //插入,插入可以不指定id,默认采用雪花算法分配id
    @Test
    public void testInsert(){
        User user = new User();
        user.setName("张三");
        user.setAge(23);
        user.setEmail("Zhangsan@163.com");
        int result = userMapper.insert(user);
    }


    //通过id删除记录
    @Test
    public void testDelete(){
        int result = userMapper.deleteById(1528308944514154497L);
        System.out.println("result:"+result);
    }


    //通过map删除记录
    // 删除name为张三,age为23的记录
    @Test
    public void testDelete01(){
        Map<String,Object> map = new HashMap<>();
        map.put("name","张三");
        map.put("age",23);
        int result = userMapper.deleteByMap(map);
    }

    //通过多个id实现批量删除
    @Test
    public void testDelete02(){
        List<Long> list= Arrays.asList(1L, 2L, 3L);
        int result = userMapper.deleteBatchIds(list);
        System.out.println(result);
    }


    //更新用户信息,修改必须指定id
    @Test
    public void testUpdate(){
        User user = new User();
        user.setId(4L);
        user.setName("李四");
        user.setEmail("Lisi@163.com");
        int result = userMapper.updateById(user);
        System.out.println(result);
    }


    //通过id查询用户信息
    @Test
    public void testSelect(){
        User user = userMapper.selectById(1L);
        System.out.println(user);
    }

    //批量查询
    @Test
    public void testSelect1(){
        List<Long> list = Arrays.asList(1L, 2L, 3L);
        List<User> users = userMapper.selectBatchIds(list);
        System.out.println(users);
    }

    //通过map删除name为Jack,age为20的记录
  //
通过map封装查询条件
  //注意:map中的key对应数据库中的列名。如:数据库user_id,实体类是userId,这时mapkey需要填写user_id
    @Test
    public void testSelect2(){
        Map<String,Object> map = new HashMap<>();
        map.put("name","Jack");
        map.put("age",20);
        List<User> list = userMapper.selectByMap(map);
        list.forEach(System.out::println);
    }

    //查询所有用户
    @Test
    public void testSelectList(){
        //查询一个东西的时候如果没有条件直接写null
        List<User> list = userMapper.selectList(null);
        list.forEach(System.out::println);
    }
}

 

posted on 2022-05-23 13:49  西凉#  阅读(55)  评论(0编辑  收藏  举报