• 欢迎光临~

BaseMapper接口crud功能

开发技术 开发技术 2022-05-23 次浏览
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
    @Autowired(required = false)
    UserMapper userMapper;
    

    //插入
    @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);
    }


    //更新用户信息
    @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的记录
    @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);
    }
}

 

程序员灯塔
转载请注明原文链接:BaseMapper接口crud功能
喜欢 (0)