栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

总结一下 Mybatis Plus -代码总结

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

总结一下 Mybatis Plus -代码总结

1.官方文档地址

https://baomidou.com/pages/24112f/

2.代码实战:
pom.xml



    4.0.0

    com.wkcto
    plus
    0.0.1-SNAPSHOT
    jar

    plus
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.0.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter
        

        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.0.5
        

        
        
            org.apache.velocity
            velocity-engine-core
            2.0
        

        
            mysql
            mysql-connector-java
            runtime
            5.1.6
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    





项目目录:
plussrcmainjavacomwkctoorderentity

package com.wkcto.order.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;


public class Dept implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.ID_WORKER)
    private String id;

    private String name;

    private String mobile;

    private Integer manager;


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public Integer getManager() {
        return manager;
    }

    public void setManager(Integer manager) {
        this.manager = manager;
    }

    @Override
    public String toString() {
        return "Dept{" +
        "id=" + id +
        ", name=" + name +
        ", mobile=" + mobile +
        ", manager=" + manager +
        "}";
    }
}

package com.wkcto.order.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;


public class Student implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String name;

    private Integer age;

    private String email;

    private Integer status;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Student{" +
        "id=" + id +
        ", name=" + name +
        ", age=" + age +
        ", email=" + email +
        ", status=" + status +
        "}";
    }
}

plussrcmainjavacomwkctoplusconfig

package com.wkcto.plus.config;

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


@Configuration
public class Config {

    
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }
}

D:学习资料plussrcmainjavacomwkctoplusentity

package com.wkcto.plus.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;


@TableName(
        value = "user_address"
)
public class Address {

    //指定主键
    @TableId(value="user_id",type  = IdType.AUTO)
    private Integer id;
    
    @TableField(value = "user_city")
    private String city;
    @TableField(value = "user_street")
    private String street;

    private String zipcode;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getZipcode() {
        return zipcode;
    }

    public void setZipcode(String zipcode) {
        this.zipcode = zipcode;
    }

    @Override
    public String toString() {
        return "Address{" +
                "id=" + id +
                ", city='" + city + ''' +
                ", street='" + street + ''' +
                ", zipcode='" + zipcode + ''' +
                '}';
    }
}

package com.wkcto.plus.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

@TableName(value = "customer")
public class Customer {

    //定义属性
    @TableId(value="id",type = IdType.AUTO)
    private Integer id;
    private String custName;//cust_name
    private int custAge;
    private String custEmail;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCustName() {
        return custName;
    }

    public void setCustName(String custName) {
        this.custName = custName;
    }

    public int getCustAge() {
        return custAge;
    }

    public void setCustAge(int custAge) {
        this.custAge = custAge;
    }

    public String getCustEmail() {
        return custEmail;
    }

    public void setCustEmail(String custEmail) {
        this.custEmail = custEmail;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", custName='" + custName + ''' +
                ", custAge=" + custAge +
                ", custEmail='" + custEmail + ''' +
                '}';
    }
}

package com.wkcto.plus.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;


public class Dept extends Model {
    //定义属性, 属性名和表的列名一样

    //uuid
    @TableId(value = "id",type = IdType.UUID)
    private String id;
    private String name;
    private String mobile;
    private Integer manager;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public Integer getManager() {
        return manager;
    }

    public void setManager(Integer manager) {
        this.manager = manager;
    }
}

package com.wkcto.plus.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;

public class Student {
    //定义属性
    @TableId(value="id",type = IdType.AUTO)
    private Integer id;
    private String name;
    private Integer age;
    private String email;
    private Integer status;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", age=" + age +
                ", email='" + email + ''' +
                ", status=" + status +
                '}';
    }
}

package com.wkcto.plus.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;

//实体类
public class User {

    //定义属性: 属性名和表中的列名一样
    
    @TableId(
            value="id",
            type = IdType.AUTO
    )
    private Integer id;
    private String name;  // null
    private String email;
    //实体类属性,推荐使用包装类型, 可以判断是否为 null
    private Integer age; // 0

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + ''' +
                ", email='" + email + ''' +
                ", age=" + age +
                '}';
    }
}

plussrcmainjavacomwkctoplusmapper

package com.wkcto.plus.mapper;

import com.baomidou.mybatisplus.core.mapper.baseMapper;
import com.wkcto.plus.entity.Address;

public interface AddressMapper extends baseMapper
{ }
package com.wkcto.plus.mapper;

import com.baomidou.mybatisplus.core.mapper.baseMapper;
import com.wkcto.plus.entity.Customer;

public interface CustomerMapper extends baseMapper {
}

package com.wkcto.plus.mapper;

import com.baomidou.mybatisplus.core.mapper.baseMapper;
import com.wkcto.plus.entity.Dept;


public interface DeptMapper extends baseMapper {
}

package com.wkcto.plus.mapper;

import com.baomidou.mybatisplus.core.mapper.baseMapper;
import com.wkcto.plus.entity.Student;

import java.util.List;

public interface StudentMapper extends baseMapper {
    //自定义方法
    public int insertStudent(Student student);
    public Student selectStudentById(Integer id);
    public List selectByName(String name);
}

package com.wkcto.plus.mapper;

import com.baomidou.mybatisplus.core.mapper.baseMapper;
import com.wkcto.plus.entity.User;


public interface UserMapper extends baseMapper {
}

plussrcmainjavacomwkctoplusPlusApplication.java

package com.wkcto.plus;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
//@MapperScan(value = "com.wkcto.plus.mapper")
@MapperScan(value = "com.wkcto.order")
public class PlusApplication {

    public static void main(String[] args) {
        SpringApplication.run(PlusApplication.class, args);
    }
}

自动生成代码
plussrcmainjavacomwkctoAutoMapper.java

package com.wkcto;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

public class AutoMapper {

    public static void main(String[] args) {
        //创建AutoGenerator ,MP中对象
        AutoGenerator ag = new AutoGenerator();

        //设置全局配置
        GlobalConfig gc  = new GlobalConfig();
        //设置代码的生成位置, 磁盘的目录
        String path = System.getProperty("user.dir");
        gc.setOutputDir(path+"/src/main/java");
        //设置生成的类的名称(命名规则)
        gc.setMapperName("%sMapper");//所有的Dao类都是Mapper结尾的,例如DeptMapper
        //设置Service接口的命名
        gc.setServiceName("%sService");//DeptService
        //设置Service实现类的名称
        gc.setServiceImplName("%sServiceImpl");//DeptServiceImpl
        //设置Controller类的命名
        gc.setControllerName("%sController");//DeptController
        //设置作者
        gc.setAuthor("changming");
        //设置主键id的配置
        gc.setIdType(IdType.ID_WORKER);
        ag.setGlobalConfig(gc);

        //设置数据源DataSource
        DataSourceConfig ds  = new DataSourceConfig();
        //驱动
        ds.setDriverName("com.mysql.jdbc.Driver");
        //设置url
        ds.setUrl("jdbc:mysql://localhost:3306/springdb");
        //设置数据库的用户名
        ds.setUsername("root");
        //设置密码
        ds.setPassword("123456");
        //把DataSourceConfig赋值给AutoGenerator
        ag.setDataSource(ds);

        //设置Package信息
        PackageConfig pc  = new PackageConfig();
        //设置模块名称, 相当于包名, 在这个包的下面有 mapper, service, controller。
        pc.setModuleName("order");
        //设置父包名,order就在父包的下面生成
        pc.setParent("com.wkcto"); //com.wkcto.order
        ag.setPackageInfo(pc);

        //设置策略
        StrategyConfig sc  = new StrategyConfig();
        sc.setNaming(NamingStrategy.underline_to_camel);
        //设置支持驼峰的命名规则
        sc.setColumnNaming(NamingStrategy.underline_to_camel);
        ag.setStrategy(sc);

        //执行代码的生成
        ag.execute();
    }
}

****测试

plussrctestjavacomwkctoplusAddressTest.java

package com.wkcto.plus;

import com.wkcto.plus.entity.Address;
import com.wkcto.plus.mapper.AddressMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AddressTest {

    //定义AddressMapper
    @Autowired
    private AddressMapper addressDao;
    @Test
    public void testInsert(){
        Address address  = new Address();
        address.setCity("上海");
        address.setStreet("南京路");
        address.setZipcode("020");
        int rows  =  addressDao.insert(address);
        System.out.println("insert address rows:"+rows);
    }


}

package com.wkcto.plus;

import com.wkcto.plus.entity.Customer;
import com.wkcto.plus.mapper.CustomerMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SuppressWarnings("all")
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerTest {

    //定义CustomerMapper
    @Autowired
    private CustomerMapper custDao;
    @Test
    public void testInsert(){
        Customer cust  = new Customer();
        cust.setCustName("张三");
        cust.setCustAge(28);
        cust.setCustEmail("zhangsan@163.com");

        int rows  = custDao.insert(cust);
        System.out.println("insert customer rows:"+rows);
    }


}

package com.wkcto.plus;

import com.wkcto.plus.entity.Dept;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DeptARTest {

    @Test
    public void testARInsert(){
        //定义dept的实体

        Dept dept  = new Dept();
        dept.setName("行政部");
        dept.setMobile("010-66666666");
        dept.setManager(5);
        //调用实体对象自己的方法,完成对象自身到数据库的添加操作
        boolean flag = dept.insert();
        System.out.println("ar insert result:"+flag);
    }


    @Test
    public void testARUpdate(){
        //定义实体Dept
        Dept dept  = new Dept();
       // dept.setId(2);
        dept.setMobile("010-22222222");
        dept.setName("改为市场部");
        dept.setManager(2);
        //根据主键id更新记录
        // UPDATE dept SET name=?, mobile=?, manager=? WHERe id=?  // id = 1
        boolean result = dept.updateById();//使用dept实体主键的值,作为where id = 1
        System.out.println("ar updateById result:"+result);
    }

    @Test
    public void testARUpdate2(){
        //定义实体Dept
        Dept dept  = new Dept();
       // dept.setId(1);
        dept.setMobile("010-3333333");
        //name , manager是没有修改的

        //根据主键id更新记录
        // UPDATE dept SET name=?, mobile=?, manager=? WHERe id=?  // id = 1
        // null的属性值不做更新处理,在update中没有null的字段
        //UPDATE dept SET mobile=? WHERe id=?
        boolean result = dept.updateById();//使用dept实体主键的值,作为where id = 1
        System.out.println("ar updateById result:"+result);
    }

    
    @Test
    public void testARDeleteById(){
        Dept dept  = new Dept();
        //DELETE FROM dept WHERe id=?
        boolean result = dept.deleteById(1);
        System.out.println("ar deleteById result:"+result);
    }

    @Test
    public void testARDeleteById2(){
        Dept dept  = new Dept();
       // dept.setId(2);
        //DELETE FROM dept WHERe id=?
        boolean result = dept.deleteById();
        System.out.println("ar deleteById result:"+result);
    }

    
   @Test
    public void testARSelectById(){
        Dept dept = new Dept();
        //设置主键的值
      // dept.setId(1);
        //调用查询方法
       //SELECT id,name,mobile,manager FROM dept WHERe id=?
       Dept dept1 = dept.selectById();
       System.out.println("ar selectById result:"+dept1);
   }

    
    @Test
    public void testARSelectById2(){
        Dept dept = new Dept();
        Dept dept1 = dept.selectById(3);
        System.out.println("dept1:"+dept1);


    }
}

package com.wkcto.plus;

import com.wkcto.plus.entity.User;
import com.wkcto.plus.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@SuppressWarnings("all")
@RunWith(SpringRunner.class)
@SpringBootTest
public class PlusApplicationTests {

    //使用自动注入, 注入Mapper对象(Dao)
    @Autowired
    private UserMapper userDao;

    //定义测试方法
    //测试添加操作, insert
    @Test
    public void testUserInsert(){
        //创建User对象


        for(int i=0;i<10;i++){
            User user  = new User();
            user.setName("zhangsan"+i);
            user.setAge(20 + i);
            user.setEmail("zhangsan@sina.com");
            //调用UserMapper的方法, 也就是父接口baseMapper中的提供的方法
            int rows = userDao.insert(user);
            System.out.println("insert 的结果:"+rows);
        }


    }

    //添加数据后,获取主键值
    @Test
    public void testInsertGetId(){
        User user  = new User();
        user.setName("李四");
        user.setAge(20);
        user.setEmail("lisi@163.com");

        int rows  = userDao.insert(user);
        System.out.println("insert user rows:"+rows);

        //获取主键id ,刚添加数据库中的数据的id
        int id = user.getId();//主键字段对应的get方法
        System.out.println("主键id:"+id);

    }

    
    @Test
    public void testUpdateUser(){
        User user = new User();
        user.setName("修改的数据");
        user.setAge(22);
        user.setEmail("edit@163.com");
        user.setId(2);
        //执行更新,根据主键值更新
        
        int rows = userDao.updateById(user);
        System.out.println("update rows:"+rows);
    }

    
    @Test
    public void testUpdateUser2(){
        User user  = new User();
        user.setId(2);
        user.setName("zhangsan");
        //更新数据
        //UPDATE user SET name=? WHERe id=?
        int i = userDao.updateById(user);
        System.out.println("i:"+i);

    }

    
    @Test
    public void testUpdateUser3(){
        User user  = new User();
        user.setId(3);
        user.setEmail("lisi@sina.com");
        //实体对象 user: [name = null , email = "lisi@sina.com" , age = 0  ]
        //没有修改 name ,age
        //判断字段是否要修改, 加入到set语句, 是根据属性值是否为null .
        //UPDATE user SET email=?, age=? WHERe id=?
        int rows = userDao.updateById(user);
        System.out.println("rows:"+rows);

    }
    
    @Test
    public void testDeleteById(){

        //DELETE FROM user WHERe id=?
        int rows  = userDao.deleteById(3);
        System.out.println("deleteById:"+rows);
    }

    
    @Test
    public void testDeleteByMap(){
        //创建Map对象,保存条件值
        Map map  = new HashMap<>();
        //put("表的字段名",条件值) , 可以封装多个条件
        map.put("name","zs");
        map.put("age",20);
        //调用删除方法
        //DELETE FROM user WHERe name = ? AND age = ?
        int rows = userDao.deleteByMap(map);
        System.out.println("deleteByMap rows:"+rows);


    }


    
    @Test
    public void deleteByBatchId(){
       

        //使用lambda创建List集合
        List ids = Stream.of(1, 2, 3, 4, 5).collect(Collectors.toList());
        //删除操作
        //DELETE FROM user WHERe id IN ( ? , ? , ? , ? , ? )
        int i = userDao.deleteBatchIds(ids);
        System.out.println("deleteBatchIds:"+i);


    }

    
    @Test
    public void testSelectById(){
        
        User user = userDao.selectById(6);
        System.out.println("selectById:"+user);

        //在使用对象之前,需要判断对象是否为null
        if(user != null){
            //业务方法的调用
        }


    }

    
    @Test
    public void testSelectBatchId(){
        List ids = new ArrayList<>();
        ids.add(6);
        ids.add(9);
        ids.add(10);

        //查询数据
        //SELECT id,name,email,age FROM user WHERe id IN ( ? , ? , ? )
        List users = userDao.selectBatchIds(ids);
        System.out.println("size:"+users.size());
        for (User u:users){
            System.out.println("查询的用户:"+u);
        }
    }

    
    @Test
    public void testSelectBatchId2(){
        List ids = Stream.of(6, 9, 10, 15).collect(Collectors.toList());
        //SELECT id,name,email,age FROM user WHERe id IN ( ? , ? , ? , ? )
        List users = userDao.selectBatchIds(ids);
        //遍历集合
        users.forEach( u -> {
            System.out.println("查询的user对象:"+u);
        });
    }

    
    @Test
    public void testSelectMap(){
        //创建Map,封装查询条件
        Map map = new HashMap<>();
        //key是字段名, value:字段值 ,多个key,是and 联接
        map.put("name","zhangsan");
        map.put("age",20);

        //根据Map查询
        //SELECT id,name,email,age FROM user WHERe name = ? AND age = ?
        List users = userDao.selectByMap(map);
        users.forEach(user -> {
            System.out.println("selectByMap:"+user);
        });

    }
}

package com.wkcto.plus;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wkcto.order.entity.Student;
import com.wkcto.order.mapper.StudentMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SuppressWarnings("all")
@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentMapperTest {

   //注入生成的StudentMapper
    @Autowired
    StudentMapper studentMapper;

    @Test
    public void testInsertStudent(){
        Student student  = new Student();
        student.setName("john");
        student.setAge(28);
        student.setEmail("john@yahu.com");
        student.setStatus(2);
        int rows  = studentMapper.insert(student);
        System.out.println("insert Student rows:"+rows);
    }

    @Test
    public void testSelect(){
        Student student = studentMapper.selectById(1);
        System.out.println("testSelect:"+student);
    }


    @Test
    public void testSelect1(){
        QueryWrapper qw = new QueryWrapper<>();
        qw.gt("age",35);
        //selectOne:查询结果只能是一条记录或没有没有记录,多条记录是报错的
        Student student = studentMapper.selectOne(qw);
        System.out.println("testSelect:"+student);
    }
}



package com.wkcto.plus;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wkcto.plus.entity.Student;
import com.wkcto.plus.mapper.StudentMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

@SuppressWarnings("all")
@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentTest {

    //定义StudentMapper
    @Autowired
    private StudentMapper studentDao;

    @Test
    public void testInsertStudent() {
        Student student = new Student();
        student.setName("李四");
        student.setEmail("li1234@163.com");
        student.setAge(22);
        student.setStatus(0);
        int rows = studentDao.insertStudent(student);
        System.out.println("inserStudent rows:" + rows);
    }

    @Test
    public void testSelectStudentById() {
        Student student = studentDao.selectStudentById(10);
        if (student != null) {
            //其他的业务操作
        }
        System.out.println("student:" + student);

    }

    @Test
    public void testSelectByName() {
        List students = studentDao.selectByName("李四");
        students.forEach(stu -> System.out.println(stu));
    }


    @Test
    public void testAllEq() {
        QueryWrapper qw = new QueryWrapper<>();
        //组装条件
        Map param = new HashMap<>();
        //map key列名 , value:查询的值
        param.put("name", "张三");
        param.put("age", 22);
        param.put("status", 1);

        qw.allEq(param);
        //调用MP自己的查询方法
        //SELECT id,name,age,email,status FROM student WHERe name = ? AND age = ?
        //WHERe name = ? AND age = ? AND status = ?
        List students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

    
    @Test
    public void testAllEq2() {
        QueryWrapper qw = new QueryWrapper<>();
        //组装条件
        Map param = new HashMap<>();
        //map key列名 , value:查询的值
        param.put("name", "张三");
        //age 是 null
        param.put("age", null);

        //allEq第二个参数为true
        qw.allEq(param, false);

        //调用MP自己的查询方法
        List students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

    
    @Test
    public void testEq() {
        QueryWrapper qw = new QueryWrapper<>();
        //组成条件
        qw.eq("name", "李四");
        //WHERe name = ?
        List students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println("查询eq:" + stu));

    }

    
    @Test
    public void testNe() {
        QueryWrapper qw = new QueryWrapper<>();
        //组成条件
        qw.ne("name", "张三");
        // WHERe name <> ?
        List students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println("查询ne:" + stu));
    }

    
    @Test
    public void testGt() {
        QueryWrapper qw = new QueryWrapper<>();
        qw.gt("age", 30); //age > 30
        // WHERe age > ?
        List students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println("stu:" + stu));
    }

    
    @Test
    public void testGe() {
        QueryWrapper qw = new QueryWrapper<>();
        qw.ge("age", 31);// >=31
        //WHERe age >= ?
        List students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println("student:" + stu));
    }

    
    @Test
    public void testLt() {
        QueryWrapper qw = new QueryWrapper<>();
        qw.lt("age", 32);
        // WHERe age < ?
        List students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println("student:" + stu));
    }

    
    @Test
    public void testLe() {
        QueryWrapper qw = new QueryWrapper<>();
        qw.le("age", 32);
        //  WHERe age <= ?
        List students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println("student:" + stu));
    }

    
    @Test
    public void testBetween() {
        QueryWrapper qw = new QueryWrapper<>();
        //between("列名",开始值,结束值)
        qw.between("age", 22, 28);
        // where age >= 12 and age < 28
        List students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

    
    @Test
    public void testNotBetween() {
        QueryWrapper qw = new QueryWrapper<>();
        qw.notBetween("age", 18, 28);
        //WHERe age NOT BETWEEN ? AND ?
        // where age < 18 or age > 28
        List students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

    
    @Test
    public void testLike() {
        QueryWrapper qw = new QueryWrapper<>();
        qw.like("name", "张");
        // WHERe name LIKE %张%
        List students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

    
    @Test
    public void testNotLike() {
        QueryWrapper qw = new QueryWrapper<>();
        qw.notLike("name", "张");
        //  WHERe name NOT LIKE ?  %张%
        List students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

    
    @Test
    public void testLikeLeft() {
        QueryWrapper qw = new QueryWrapper<>();
        qw.likeLeft("name", "张");
        //WHERe name LIKE %张
        List students = studentDao.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

    
    @Test
    public void testLikeRight() {
        QueryWrapper qw = new QueryWrapper<>();
        qw.likeRight("name", "李");
        //WHERe name LIKE 李%
        List students = studentDao.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }


    
    @Test
    public void testIsNull(){
        QueryWrapper qw = new QueryWrapper<>();
        //判断email is null
        //WHERe email IS NULL
        qw.isNull("email");
        print(qw);
    }


    
    @Test
    public void testIsNotNull(){
        QueryWrapper qw = new QueryWrapper<>();
        // WHERe email IS NOT NULL
        qw.isNotNull("email");
        print(qw);
    }

    
    @Test
    public void testIn(){
        QueryWrapper qw = new QueryWrapper<>();
        //in(列名,多个值的列表)
        //WHERe name IN (?,?,?)
        qw.in("name","张三","李四","周丽");
        print(qw);

    }

    
    @Test
    public void testNoIn(){
        QueryWrapper qw = new QueryWrapper<>();
        //in(列名,多个值的列表)
        //WHERe name NOT IN (?,?,?)
        qw.notIn("name","张三","李四","周丽");
        print(qw);

    }
    
    @Test
    public void testIn2(){
        QueryWrapper qw = new QueryWrapper<>();
        List list = new ArrayList<>();
        list.add(1);
        list.add(2);
        //WHERe status IN (?,?)
        qw.in("status",list);
        print(qw);


    }


    
    @Test
    public void testInSQL(){
        QueryWrapper qw = new QueryWrapper<>();
        //WHERe age IN (select age from student where id=1)
        qw.inSql("age","select age from student where id=1");
        print(qw);
    }


    
    @Test
    public void testNotInSQL(){
        QueryWrapper qw = new QueryWrapper<>();
        //WHERe age NOT IN (select age from student where id=1)
        qw.notInSql("age","select age from student where id=1");
        print(qw);
    }

    private void print(QueryWrapper qw){
        List students = studentDao.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

    
    @Test
    public void testGroupby(){
        QueryWrapper qw = new QueryWrapper<>();
        qw.select("name,count(*) personNumbers");//select name,count(*) personNumbers
        qw.groupBy("name");
        // SELECT name,count(*) personNumbers FROM student GROUP BY name
        print(qw);
    }

    
    @Test
    public void testOrderByAsc(){
        QueryWrapper qw= new QueryWrapper<>();
        //FROM student ORDER BY name ASC , age ASC
        qw.orderByAsc("name","age");
        print(qw);
    }

    
    @Test
    public void testOrderByDesc(){
        QueryWrapper qw= new QueryWrapper<>();
        // ORDER BY name DESC , id DESC
        qw.orderByDesc("name","id");
        print(qw);
    }

    
    @Test
    public void testOrder(){
        QueryWrapper qw = new QueryWrapper<>();
        qw.orderBy(true,true,"name")
                .orderBy(true,false,"age")
                .orderBy(true,false,"email");
        // name asc, age desc , email desc
        //FROM student ORDER BY name ASC , age DESC , email DESC
        print(qw);
    }

    
    @Test
    public void testOr(){
        QueryWrapper qw= new QueryWrapper<>();
        //WHERe name = ? OR age = ?
        qw.eq("name","张三")
                .or()
                .eq("age",22);
        print(qw);
    }

    
    @Test
    public void testLast(){
        QueryWrapper qw = new QueryWrapper<>();
        //SELECt id,name,age,email,status FROM student WHERe name = ? OR age = ? limit 1
        qw.eq("name","张三")
                .or()
                .eq("age",22)
                .last("limit 1");
        print(qw);

    }

    
    @Test
    public void testExists(){
        QueryWrapper qw= new QueryWrapper<>();
        //SELECt id,name,age,email,status FROM student
        // WHERe EXISTS (select id from student where age > 20)
        //qw.exists("select id from student where age > 90");

        //SELECt id,name,age,email,status FROM student WHERe
        // NOT EXISTS (select id from student where age > 90)

        qw.notExists("select id from student where age > 90");
        print(qw);
    }


    
    @Test
    public void testPage(){
        QueryWrapper qw = new QueryWrapper<>();
        qw.gt("age",22);
        IPage page  = new Page<>();
        //设置分页的数据
        page.setCurrent(1);//第一页
        page.setSize(3);// 每页的记录数

        IPage result = studentDao.selectPage(page,qw);

        //获取分页后的记录
        List students = result.getRecords();
        System.out.println("students.size()="+students.size());
        //分页的信息
        long pages  = result.getPages();
        System.out.println("页数:"+pages);
        System.out.println("总记录数:"+result.getTotal());
        System.out.println("当前页码:"+result.getCurrent());
        System.out.println("每页的记录数:"+result.getSize());
    }


}





转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号