总结一下 Mybatis Plus -代码总结

574 篇文章 4 订阅

1.官方文档地址

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

2.代码实战:
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wkcto</groupId>
    <artifactId>plus</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>plus</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>

        <!-- 模板引擎 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>


项目目录:
plus\src\main\java\com\wkcto\order\entity

package com.wkcto.order.entity;

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

/**
 * <p>
 * 
 * </p>
 *
 * @author changming
 * @since 2018-12-26
 */
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;

/**
 * <p>
 * 
 * </p>
 *
 * @author changming
 * @since 2018-12-26
 */
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 +
        "}";
    }
}

plus\src\main\java\com\wkcto\plus\config

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标注的类就相当于xml配置文件
 */
@Configuration
public class Config {

    /***
     * 定义方法,返回的返回值是java 对象,这个对象是放入到spring容器中
     * 使用@Bean修饰方法
     * @Bean等同于<bean></bean>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }
}

D:\学习资料\plus\src\main\java\com\wkcto\plus\entity

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="表名")
 * 位置:在类定义的上面
 */
@TableName(
        value = "user_address"
)
public class Address {

    //指定主键
    @TableId(value="user_id",type  = IdType.AUTO)
    private Integer id;
    /**
     * @TableField : 指定属性和列名的对应关系。
     *    属性: value 指定列名
     */
    @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;

/**
 * 使用AR,要求实体类需要继承MP中的Model
 * Model中提供了对数据库的CRUD的操作
 */
public class Dept extends Model<Dept> {
    //定义属性, 属性名和表的列名一样

    //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 {

    //定义属性: 属性名和表中的列名一样
    /**
     * 指定主键的方式:
     * value:主键字段的名称, 如果是id,可以不用写。
     * type:指定主键的类型, 主键的值如何生成。 idType.AUTO 表示自动增长。
     */
    @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 +
                '}';
    }
}

plus\src\main\java\com\wkcto\plus\mapper

package com.wkcto.plus.mapper;

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

public interface AddressMapper extends BaseMapper<Address> {
}

package com.wkcto.plus.mapper;

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

public interface CustomerMapper extends BaseMapper<Customer> {
}

package com.wkcto.plus.mapper;

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

/**
 * DeptMapper是不需要使用的,MP需要使用DeptMapper获取到数据库的表的信息。
 * 如果不定义DeptMapper, MP会报错, 找不到表的定义信息
 */
public interface DeptMapper extends BaseMapper<Dept> {
}

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<Student> {
    //自定义方法
    public int insertStudent(Student student);
    public Student selectStudentById(Integer id);
    public List<Student> selectByName(String name);
}

package com.wkcto.plus.mapper;

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

/**
 * 自定义Mapper,就是Dao接口。
 * 1.要实现BaseMapper
 * 2.指定实体类
 *
 * BaseMapper是MP框架中的对象,定义17个操作方法(CRUD)
 */
public interface UserMapper extends BaseMapper<User> {
}

plus\src\main\java\com\wkcto\plus\PlusApplication.java

package com.wkcto.plus;

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

/**
 * @MapperScan:扫描器,指定Mapper类所在的包
 */
@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);
    }
}

自动生成代码
plus\src\main\java\com\wkcto\AutoMapper.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();
    }
}

****测试

plus\src\test\java\com\wkcto\plus\AddressTest.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);
    }

    /**
     * deleteById()删除操作即使没有从数据库中删除数据,也返回是true
     */
    @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);
    }

    /**
     * selectByID
     * 1.按实体的主键能查找出数据,返回对象
     * 2.按实体的主键不能查出数据,是null ,不报错。
     */
   @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);
   }

    /**
     * selectById(主键)
     * 1.主键有记录,返回实体对象
     * 2.主键没有记录,返回是null
     *
     */
    @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);

    }

    /**
     * 更新操作update
     */
    @Test
    public void testUpdateUser(){
        User user = new User();
        user.setName("修改的数据");
        user.setAge(22);
        user.setEmail("edit@163.com");
        user.setId(2);
        //执行更新,根据主键值更新
        /*UPDATE user SET name=?, email=?, age=? WHERE id=?
         *更新了所有非null属性值, 条件where id = 主键值
         */
        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);

    }

    /**
     * 更新数据: 实体类的属性是基本类型 - int age
     */
    @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);

    }
    /**
     * 按主键删除一条数据
     * 方法是deleteById()
     * 参数:主键值
     * 返回值:是删除的成功记录数
     */
    @Test
    public void testDeleteById(){

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

    /**
     * 按条件删除数据, 条件是封装到Map对象中
     * 方法:deleteByMap(map对象);
     * 返回值:删除成功的记录数
     */
    @Test
    public void testDeleteByMap(){
        //创建Map对象,保存条件值
        Map<String,Object> 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);


    }


    /**
     * 批处理方式:使用多个主键值,删除数据
     * 方法名称:deleteBatchIds()
     * 参数: Collection<? extends Serializable> var1
     * 返回值:删除的记录数
     */
    @Test
    public void deleteByBatchId(){
       /* List<Integer> ids  = new ArrayList<>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        ids.add(4);
        ids.add(5);*/

        //使用lambda创建List集合
        List<Integer> 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);


    }

    /**
     * 实现查询 selectById ,根据主键值查询
     * 参数:主键值:
     * 返回值: 实体对象(唯一的一个对象)
     */
    @Test
    public void testSelectById(){
        /**
         * 生成的sql: SELECT id,name,email,age FROM user WHERE id=?
         * 如果根据主键没有查找到数据, 得到的返回值是 null
         */
        User user = userDao.selectById(6);
        System.out.println("selectById:"+user);

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


    }

    /**
     * 实现批处理查询,根据多个主键值查询, 获取到List
     * 方法:selectBatchIds
     * 参数:id的集合
     * 返回值:List<T>
     */
    @Test
    public void testSelectBatchId(){
        List<Integer> ids = new ArrayList<>();
        ids.add(6);
        ids.add(9);
        ids.add(10);

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

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

    /**
     * 使用Map做多条件查询
     * 方法:selectByMap()
     * 参数:Map<String,Object>
     * 返回值:List<T>
     *
     */
    @Test
    public void testSelectMap(){
        //创建Map,封装查询条件
        Map<String,Object> 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<User> 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<Student> 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<Student> students = studentDao.selectByName("李四");
        students.forEach(stu -> System.out.println(stu));
    }


    @Test
    public void testAllEq() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //组装条件
        Map<String, Object> param = new HashMap<>();
        //map<key,value> 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<Student> students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

    /**
     * 1) Map对象中有 key的value是null
     * 使用的是 qw.allEq(param,true);
     * 结果:WHERE name = ? AND age IS NULL
     * <p>
     * 2) Map对象中有 key的value是null
     * qw.allEq(param,false);
     * 结果:WHERE name = ?
     * <p>
     * 结论:
     * allEq(map,boolean)
     * true:处理null值,where 条件加入 字段 is null
     * false:忽略null ,不作为where 条件
     */
    @Test
    public void testAllEq2() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //组装条件
        Map<String, Object> param = new HashMap<>();
        //map<key,value> key列名 , value:查询的值
        param.put("name", "张三");
        //age 是 null
        param.put("age", null);

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

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

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

    }

    /**
     * ne使用
     * ne表示不等于 <>
     * <p>
     * ne("列名",值)
     */
    @Test
    public void testNe() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //组成条件
        qw.ne("name", "张三");
        // WHERE name <> ?
        List<Student> students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println("查询ne:" + stu));
    }

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

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

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

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

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

    /**
     * notBetween(不在范围区间内)
     */
    @Test
    public void testNotBetween() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.notBetween("age", 18, 28);
        //WHERE age NOT BETWEEN ? AND ?
        // where age < 18 or age > 28
        List<Student> students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

    /**
     * like 匹配某个值
     */
    @Test
    public void testLike() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.like("name", "张");
        // WHERE name LIKE %张%
        List<Student> students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

    /**
     * notLike 不匹配某个值
     */
    @Test
    public void testNotLike() {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.notLike("name", "张");
        //  WHERE name NOT LIKE ?  %张%
        List<Student> students = studentDao.selectList(qw);
        students.forEach(stu -> System.out.println(stu));
    }

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

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


    /**
     * isNull , 判断字段是 null
     */
    @Test
    public void testIsNull(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        //判断email is null
        //WHERE email IS NULL
        qw.isNull("email");
        print(qw);
    }


    /**
     * isNotNull , 判断字段是 is not null
     */
    @Test
    public void testIsNotNull(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        // WHERE email IS NOT NULL
        qw.isNotNull("email");
        print(qw);
    }

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

    }

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

    }
    /**
     * in 值列表
     */
    @Test
    public void testIn2(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        List<Object> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        //WHERE status IN (?,?)
        qw.in("status",list);
        print(qw);


    }


    /**
     * inSql() : 使用子查询
     */
    @Test
    public void testInSQL(){
        QueryWrapper<Student> 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);
    }


    /**
     * notInSql() : 使用子查询
     */
    @Test
    public void testNotInSQL(){
        QueryWrapper<Student> 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<Student> students = studentDao.selectList(qw);
        students.forEach(student -> System.out.println(student));
    }

    /**
     * groupBy:分组
     */
    @Test
    public void testGroupby(){
        QueryWrapper<Student> 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);
    }

    /**
     * orderbyAsc : 按字段升序
     */
    @Test
    public void testOrderByAsc(){
        QueryWrapper<Student> qw= new QueryWrapper<>();
        //FROM student ORDER BY name ASC , age ASC
        qw.orderByAsc("name","age");
        print(qw);
    }

    /**
     * orderbyDesc : 按字段降序
     */
    @Test
    public void testOrderByDesc(){
        QueryWrapper<Student> qw= new QueryWrapper<>();
        // ORDER BY name DESC , id DESC
        qw.orderByDesc("name","id");
        print(qw);
    }

    /**
     * order :指定字段和排序方向
     *
     * boolean condition : 条件内容是否加入到 sql语句的后面。
     * true:条件加入到sql语句
     * FROM student ORDER BY name ASC
     *
     * false:条件不加入到sql语句
     * FROM student
     */
    @Test
    public void testOrder(){
        QueryWrapper<Student> 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);
    }

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

    /**
     * last : 拼接sql语句到MP的sql语句的最后
     */
    @Test
    public void testLast(){
        QueryWrapper<Student> 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);

    }

    /**
     * exists : 判断条件
     *
     * notExists
     */
    @Test
    public void testExists(){
        QueryWrapper<Student> 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);
    }


    /**
     * 分页:
     * 1.统计记录数,使用count(1)
     *    SELECT COUNT(1) FROM student WHERE age > ?
     * 2.实现分页,在sql语句的末尾加入 limit 0,3
     *    SELECT id,name,age,email,status FROM student WHERE age > ? LIMIT 0,3
     */
    @Test
    public void testPage(){
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.gt("age",22);
        IPage<Student> page  = new Page<>();
        //设置分页的数据
        page.setCurrent(1);//第一页
        page.setSize(3);// 每页的记录数

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

        //获取分页后的记录
        List<Student> 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());
    }


}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值