Mybatis-Plus入门 进阶篇

文章目录

  • 本次学习目的
  • 创建环境
    • 实体类User
      • 关于乐观锁
        • 插件配置
    • 枚举类SexEnum
    • 启动类MyApplication
    • MybatisPlus(MP)配置类
    • FindAll 自定义的sql方法类
    • MySqlInjector 把自己写的方法给注入到spring中
    • mapper
      • MyBaseMapper
      • UserMapper
    • MyInterceptor 插件类
    • MyMetaObjectHandler 填充
    • 配置文件
      • UserMapper.xml
      • application.properties spring配置文件
      • log4j 日志配置文件
      • mybatis配置文件
      • maven文件
  • 测试
    • 测试UserMapper
    • 关于QueryWrapper
      • 基本比较操作有
      • 模糊查询
      • 排序
      • 逻辑查询
    • 测试user

本次学习目的

SpringBoot + Mybatis + MP进行进一步简化整合
由于使用SpringBoot需要继承parent,所以需要重新创建工程,并不是创建子Module。所以就不能用在和基础篇的内容所在的同一个工程下面了

创建环境

Mybatis-Plus入门 进阶篇_第1张图片
Mybatis-Plus入门 进阶篇_第2张图片
Mybatis-Plus入门 进阶篇_第3张图片

实体类User

package com.tong.pojo;

import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.tong.enums.SexEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User extends Model<User> {
/*	这里实体对象继承Model是为了开启AR 这样就可以直接用 
	user.selectbyid(id) 这种形式来查数据了
	*/

    @TableId(type = IdType.AUTO) 
    //指定id类型为自增长
    private Long id;
    private String user_name;
    @TableField(select = false,fill = FieldFill.INSERT) 
    //查询的时候不查询password
    private String password;
    private String name;
    private Integer age;
    @TableField(exist = false) //数据库里面不存在address这一项
    private String address;
    @TableField(value="email" )
    //指定数据库里面的名字
    private String mail;


    @Version //乐观锁的版本字段
    private Integer version;

    @TableLogic//逻辑删除字段  1是删除 0是未删除
    private Integer deleted;

    private SexEnum sex;

}

关于乐观锁

意图:
当要更新一条记录的时候,希望这条记录没有被别人更新

乐观锁实现方式:

  • 取出记录时,获取当前version
  • 更新时,带上这个version
  • 执行更新时, set version = newVersion where version = oldVersion
    如果version不对,就更新失败

插件配置

spring xml:

<bean class="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"/>

spring boot:

@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}

枚举类SexEnum

package com.tong.enums;

import com.baomidou.mybatisplus.core.enums.IEnum;

public enum SexEnum implements IEnum<Integer> {

    MAN(1,"男"),
    WOMAN(2,"女");

    private int value;
    private String desc;

    SexEnum(int value, String desc) {
        this.value = value;
        this.desc = desc;
    }

    @Override
    public Integer getValue() {
        return this.value;
    }

    @Override
    public String toString() {
        return this.desc;
    }
}

启动类MyApplication

package com.tong;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//@MapperScan("com.tong.mapper") 扫描交给MP配置类了
@SpringBootApplication
public class MyApplication {

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

}

MybatisPlus(MP)配置类

package com.tong;

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

@Configuration
@MapperScan("com.tong.mapper") //设置mapper接口的扫描包
public class MybatisPlusConfig {


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

@Bean //注入自定义的拦截器(插件)
public MyInterceptor myInterceptor(){
    return new MyInterceptor(); //这个就是我们自己写的插件
}

@Bean //注入自定义方法
public MySqlInjector mySqlInjector(){
    return new MySqlInjector();
}


}

FindAll 自定义的sql方法类

package com.tong.injectors;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

public class FIndAll extends AbstractMethod {
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql="SELECT * FROM "+tableInfo.getTableName();
        SqlSource sqlSource = languageDriver.createSqlSource(configuration,sql, modelClass);

        return this.addSelectMappedStatement(mapperClass, "findAll", sqlSource, modelClass, tableInfo);

    }
}

MySqlInjector 把自己写的方法给注入到spring中

package com.tong.injectors;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.AbstractSqlInjector;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;

import java.util.ArrayList;
import java.util.List;
                             //   AbstractSqlInjector继承这个会导致之前的所有方法失效
public class MySqlInjector extends DefaultSqlInjector {
                                    //DefaultSqlInjector 是AbstractSqlInjector的一个子类
                                    // 继承通过再加载到List中来让这个类也能有父类的方法
    @Override
    public List<AbstractMethod> getMethodList() {
        ArrayList<AbstractMethod> abstractMethods = new ArrayList<>();
        abstractMethods.add(new FIndAll());//把自己写的方法给加载进去
        abstractMethods.addAll(super.getMethodList());//把父类的方法都加进去
        return abstractMethods;
    }
}

注意: 如果不extends DefaultSqlInjector就会 导致方法里面只有插入的FindAll方法 MP自带的方法都会消失不能用了

mapper

MyBaseMapper

package com.tong.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import java.util.List;

public interface MyBaseMapper<T> extends BaseMapper<T> {
    List<T> findAll(); //通过上面的FIndAll来实现

}

UserMapper

package com.tong.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tong.pojo.User;

public interface UserMapper extends MyBaseMapper<User>  {

    User my_findById(long id); //通过xml来实现

}

MyInterceptor 插件类

插件的意思就是 在发送数据 和接收数据的时候对数据进行一些处理
改变刚发出去和刚刚收到的数据的内容
这里的例子是阻止updat方法的使用

package com.tong.plugins;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.parsers.BlockAttackSqlParser;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.SqlExplainInterceptor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Intercepts({@Signature(
        type= Executor.class,
        method = "update",//这个插件只针对update方法
        args = {MappedStatement.class,Object.class})})
public class MyInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //拦截方法,具体业务逻辑编写的位置
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        //创建target对象的代理对象,目的是将当前拦截器加入到该对象中
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        //属性设置
    }
    @Bean//sql拦截器插件
    public SqlExplainInterceptor sqlExplainInterceptor(){
        SqlExplainInterceptor sqlExplainInterceptor = new SqlExplainInterceptor();
        List<ISqlParser> sqlParserList = new ArrayList<>();
        // 攻击 SQL 阻断解析器、加入解析链
        sqlParserList.add(new BlockAttackSqlParser());
        sqlExplainInterceptor.setSqlParserList(sqlParserList);
        return sqlExplainInterceptor;
    }


}

MyMetaObjectHandler 填充

package com.tong.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

@Component //让spring扫描到 然后加载到spring容器里面
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //获取password的数值  为空就填充 不为空就不填充
        Object password = getFieldValByName("password", metaObject);
        if (password==null){
            setFieldValByName("password","666666",metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {

    }
}

配置文件

UserMapper.xml


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tong.mapper.UserMapper">

    <select id="my_findById" resultType="user">
        select * from tb_user where id = #{id}
    select>

mapper>

application.properties spring配置文件

spring.application.name = mybatis_plus_spring_boot
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
#指定全局配置文件
mybatis-plus.config-location=classpath:mybatis-config.xml

#指定自定义sql语句的xml文件的位置
mybatis-plus.mapper-locations = classpath*:mybatis/*.xml
#实体对象的扫描包
mybatis-plus.type-aliases-package = com.tong.pojo

#告诉插件 删除状态的值是1
mybatis-plus.global-config.db-config.logic-delete-value=1
#未删除状态的数值为0
mybatis-plus.global-config.db-config.logic-not-delete-value=0

# 枚举包扫描                         扫描包下面的所有枚举然后加载到plus里面
mybatis-plus.type-enums-package=com.tong.enums

log4j 日志配置文件

log4j.rootLogger=DEBUG,A1

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%t] [%c]-[%p] %m%n

mybatis配置文件


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <plugins>
        
        <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor">
            
            <property name="maxTime" value="100"/>
            
            <property name="format" value="true"/>
        plugin>
        
        <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor"/>

    plugins>



configuration>

maven文件



<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.0modelVersion>

  <groupId>cn.itcast.mpgroupId>
  <artifactId>itcast-mp-springbootartifactId>
  <version>1.0-SNAPSHOTversion>


  <name>mybatis_plus_spring_bootname>
  
  <url>http://www.example.comurl>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.7maven.compiler.source>
    <maven.compiler.target>1.7maven.compiler.target>
  properties>

  <parent>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-parentartifactId>
    <version>2.1.4.RELEASEversion>
  parent>


  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>

    <dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starterartifactId>
    <exclusions>
    <exclusion>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-loggingartifactId>
    exclusion>
    exclusions>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-starter-testartifactId>
      <scope>testscope>
    dependency>
    
    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
      <optional>trueoptional>
    dependency>
    
    <dependency>
      <groupId>com.baomidougroupId>
      <artifactId>mybatis-plus-boot-starterartifactId>
      <version>3.1.1version>
    dependency>
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.47version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
    dependency>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-testartifactId>
    dependency>
    <dependency>
      <groupId>org.springframework.bootgroupId>
      <artifactId>spring-boot-testartifactId>
    dependency>

  dependencies>

  <build>
    <pluginManagement>
      <plugins>

          <plugin>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-maven-pluginartifactId>
          plugin>

        
        <plugin>
          <artifactId>maven-clean-pluginartifactId>
          <version>3.1.0version>
        plugin>
        
        <plugin>
          <artifactId>maven-resources-pluginartifactId>
          <version>3.0.2version>
        plugin>
        <plugin>
          <artifactId>maven-compiler-pluginartifactId>
          <version>3.8.0version>
        plugin>
        <plugin>
          <artifactId>maven-surefire-pluginartifactId>
          <version>2.22.1version>
        plugin>
        <plugin>
          <artifactId>maven-jar-pluginartifactId>
          <version>3.0.2version>
        plugin>
        <plugin>
          <artifactId>maven-install-pluginartifactId>
          <version>2.5.2version>
        plugin>
        <plugin>
          <artifactId>maven-deploy-pluginartifactId>
          <version>2.8.2version>
        plugin>
        
        <plugin>
          <artifactId>maven-site-pluginartifactId>
          <version>3.7.1version>
        plugin>
        <plugin>
          <artifactId>maven-project-info-reports-pluginartifactId>
          <version>3.0.0version>
        plugin>
      plugins>
    pluginManagement>
  build>
project>

测试

测试UserMapper

package org.example;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tong.MyApplication;
import com.tong.enums.SexEnum;
import com.tong.mapper.UserMapper;
import com.tong.pojo.User;
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.SpringJUnit4ClassRunner;

import java.util.*;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes= MyApplication.class)
public class TestUserMapper {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void test(){
        User user = new User();
        user.setMail("12345.com");
        user.setAge(20);
        user.setUser_name("caocao1");
        user.setName("曹操1234");
        user.setPassword("123456");
        user.setAddress("北京");
        int insert = userMapper.insert(user);
        System.out.println(insert);
        System.out.println(user.getId());
    }



    @Test
    public void testupdate(){
        User user = new User();
        user.setId(9L);
//        user.setMail("2212345.com");
//        user.setAge(2220);
//        user.setUser_name("22caocao1");
//        user.setName("22曹操12");
        user.setPassword("322123456"); //设置更新的内容
        user.setAddress("3322北京");
        int insert = userMapper.updateById(user);
        System.out.println(insert);
        System.out.println(user.getId());
    }

@Test
    public void userQueryWrappermethod(){
             User user = new User();
             user.setAge(333);
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_name","zhangsan");
            //这个是更新条件 满足 user_name 是zhangsan
             this.userMapper.update(user,userQueryWrapper);
}
@Test
    public void updateWrappermethod() {
    UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
    userUpdateWrapper.set("age",222).set("password",99999).eq("id",2);
    //set是确定更新的属性名和更新的内容   eq还是确定更新的条件
    this.userMapper.update(null,userUpdateWrapper);
}
@Test
    public void deletebyid() {
    int i = this.userMapper.deleteById(15L);
    System.out.println("result="+i);
}
        @Test
    public void UserMapperdelete(){
            Map<String,Object> map = new HashMap<>();
            map.put("user_name","zhangsan");
            map.put("id","10");
            //根据map删除数据多个条件之间是and关系
            int i = this.userMapper.deleteByMap(map);
            System.out.println("result="+i);
        }
    @Test
    public void Userdelete_two_method() {
        int delete;
        if (true) {
            //通过user对象设置删除条件
            User user = new User();
            user.setId(5L);
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(user);
                //这里的QUeryWrapper要把user对象当作参数传入进去
             delete = this.userMapper.delete(userQueryWrapper);
        }else{
            //通过QueryWrapper的eq来设置条件
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("password","123456").eq("user_name","123456");
             delete = this.userMapper.delete(userQueryWrapper);

        }
        System.out.println("result="+delete);
    }
        @Test
    public void testselectById() {
            User user = this.userMapper.selectById(15L);
            System.out.println(user);
        }

    @Test
    public void testselectByIds() {
        List<User> user = this.userMapper.selectBatchIds(Arrays.asList(2L,3L,4L));
        for (User user1 : user) {
            System.out.println(user1);
        }

    }
@Test
    public void selectforone(){
    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
     userQueryWrapper.eq("id", "2");
    User user = this.userMapper.selectOne(userQueryWrapper);
    System.out.println(user);
}
@Test
    public void selectforcount(){
    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
    userQueryWrapper.gt("age",10);
    //根据条件查行数
    Integer integer = this.userMapper.selectCount(userQueryWrapper);
    System.out.println(integer);
}
@Test
    public void selectliest(){
    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
    userQueryWrapper.gt("age",10);
    List<User> users = this.userMapper.selectList(userQueryWrapper);
    for (User user : users) {
        System.out.println(user);
    }
}
@Test
    public void testselectpage(){
    Page<User> userPage = new Page<>(1,2);
    //查询第一页两条数据
    QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
    userQueryWrapper.gt("age",10);
    IPage<User> userIPage = this.userMapper.selectPage(userPage, userQueryWrapper);
    List<User> records = userIPage.getRecords();
    for (User record : records) {
        System.out.println(record);
    }

    System.out.println("总条数"+userIPage.getTotal());
    System.out.println("总页数"+userIPage.getPages());
    System.out.println("当前页数"+userIPage.getCurrent());


}
@Test
public void myFindById(){
    User user = this.userMapper.my_findById(2L);

    System.out.println(user);
}
    @Test
    public void testWrapper() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
//设置条件
        Map<String,Object> params = new HashMap<>();
        params.put("name", "张三");

        params.put("password", null);
        //wrapper.allEq(params);
        wrapper.allEq(params,false);
        List<User> users = this.userMapper.selectList(wrapper);
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void testEq() {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
//SELECT id,user_name,password,name,age,email FROM tb_user WHERE password = ?
    //    AND age >= ? AND name IN (?,?,?)
        wrapper.eq("password", "123456")
                .ge("age", 20)
                .in("name", "李四", "王五", "赵六");
        List<User> users = this.userMapper.selectList(wrapper);
        for (User user : users) {
            System.out.println(user);
        }
    }
    @Test
    public void testUpdate(){
        User user = new User();
        user.setAge(20);
        int result = this.userMapper.update(user, null);
        System.out.println("result = " + result);
    }

    @Test
    public void testFindAll(){
        List<User> users = this.userMapper.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }
    @Test
    public void testInsert(){
        User user = new User();
        user.setAge(24);
        user.setUser_name("野兽仙贝");
        user.setName("yeshou");
        user.setAddress("霓虹");
        user.setMail("123");
        int insert = this.userMapper.insert(user);
        System.out.println(insert);
    }
}

关于QueryWrapper

QueryWrapper这个对象之间翻译过来的意思是 询问包装器
显而易见这个是来包装查询条件的

基本比较操作有

  • eq
    等于 =
  • ne
    不等于 <>
  • gt
    大于 >
  • ge
    大于等于 >=
  • lt
    小于 <
  • le
    小于等于 <=
  • between
    BETWEEN 值1 AND 值2
  • notBetween
    NOT BETWEEN 值1 AND 值2
  • in
    字段 IN (value.get(0), value.get(1), …)

模糊查询

  • like
    LIKE ‘%值%’
    例: like(“name”, “王”) —> name like ‘%王%’
  • notLike
    NOT LIKE ‘%值%’
    例: notLike(“name”, “王”) —> name not like ‘%王%’
  • likeLeft
    LIKE ‘%值’
    例: likeLeft(“name”, “王”) —> name like ‘%王’
  • likeRight
    LIKE ‘值%’
    例: likeRight(“name”, “王”) —> name like ‘王%’
package cn.itcast.mp;
import cn.itcast.mp.mapper.UserMapper;
import cn.itcast.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testWrapper() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
//SELECT id,user_name,password,name,age,email FROM tb_user WHERE name LIKE ?
//Parameters: %曹%(String)
wrapper.like("name", "曹");
List<User> users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
}

排序

  • orderBy
    排序:ORDER BY 字段, …
    例: orderBy(true, true, “id”, “name”) —> order by id ASC,name ASC
  • orderByAsc
    排序:ORDER BY 字段, … ASC
    例: orderByAsc(“id”, “name”) —> order by id ASC,name ASC
  • orderByDesc
    排序:ORDER BY 字段, … DESC
    例: orderByDesc(“id”, “name”) —> order by id DESC,name DESC

逻辑查询

  • or
    拼接 OR
    主动调用 or 表示紧接着下一个方法不是用 and 连接!(不调用 or 则默认为使用 and 连接)
  • and
    AND 嵌套
    例: and(i -> i.eq(“name”, “李白”).ne(“status”, “活着”)) —> and (name = ‘李白’ and status
    <> ‘活着’)
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
public void testWrapper() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
//SELECT id,user_name,password,name,age,email FROM tb_user WHERE name = ? OR
age = ?
wrapper.eq("name","李四").or().eq("age", 24);
List<User> users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
}

测试user

package org.example;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tong.MyApplication;
import com.tong.enums.SexEnum;
import com.tong.mapper.UserMapper;
import com.tong.pojo.User;
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.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes= MyApplication.class)
public class TestUSerMapper2 {
    @Test
    public void test(){
        User user = new User();
        user.setId(2L);
        User user1 = user.selectById();
        System.out.println(user1);
    }

    @Test
    public void testinsert(){
        User user = new User();
        user.setUser_name("diaochan");
        user.setPassword("123456");
        user.setAge(20);
        user.setName("貂蝉");
        user.setMail("[email protected]");

        // 调用AR的insert方法进行插入数据
        boolean insert = user.insert();
        System.out.println("result => " + insert);
    }

    @Test
    public void testupdate(){
        User user = new User();
        user.setId(13L);
        user.setAge(30);
        boolean b = user.updateById();
        System.out.println(b);

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("age","30");
        List<User> users = user.selectList(userQueryWrapper);
        for (User user1 : users) {
            System.out.println(user1);
        }
    }

    @Test
    public void testdelete(){
        User user = new User();
        Integer integer = user.selectCount(null);
        user.setId(13L);

        System.out.println(integer.toString());

        user.deleteById();
        System.out.println(user.selectCount(null));
    }


    @Test
    public void testselect(){
        User user = new User();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.ge("age","10");
        userQueryWrapper.select("id", "name", "age");
        List<User> users = user.selectList(userQueryWrapper);

        for (User user1 : users) {

            System.out.println(user1);
        }

    }
    @Test
    public void testUpdate(){
        User user = new User();
        boolean update = user.update(null);
        System.out.println("result = " + update);
    }
    @Test
    public void testselect1(){
        User user = new User();
        List<User> users = user.selectList(null);
        for (User user1 : users) {
            System.out.println(user1);

        }
    }

    @Test
    public void testUpdateVersion(){
        User user = new User();
        user.setId(4L);// 查询条件
        user.setAge(24); // 更新的数据
        user.setVersion(8); // 当前的版本信息
        boolean result = user.updateById();
        System.out.println("result => " + result);
    }

    @Test
    public void testInsert(){
        User user = new User();
        user.setAge(24);
        user.setUser_name("野兽仙贝");
        user.setName("yeshou");
        user.setAddress("霓虹");
        user.setMail("123");
        boolean insert = user.insert();

    }


    @Test
    public void testInsert1(){
        User user = new User();
        user.setUser_name("diaochan");
        user.setPassword("123456");
        user.setAge(20);
        user.setName("貂蝉");
        user.setMail("[email protected]");
        user.setVersion(1);
        user.setSex(SexEnum.WOMAN); //使用的是枚举

        // 调用AR的insert方法进行插入数据
        boolean insert = user.insert();
        System.out.println("result => " + insert);
    }
}

你可能感兴趣的:(mybatis-plus,java,spring,boot,intellij-idea,mybatis)