Mybatis-Plus系列--进阶实例

其他网址

一文MyBatis-Plus快速入门 - 享智同行 - 博客园
mybatis-plus的使用 ------ 进阶 - 简书

本项目所有源码:https://gitee.com/shapeless/demo_MybtisPlus/tree/master/Complex

自定义SQL

其他网址

mybatis-plus之自定义sql、分页、Wrapper_CDN-CSDN博客_mybatisplus wrapper分页
Mybatisplus 自定义sql 使用条件构造器 - 静水165 - 博客园

自定义的sql使用Wrapper对版本有要求:mybatis-plus版本需要大于或等于3.0.7。

简介

含义
ew.customSqlSegment 条件构造器(Wrapper)
ew.sqlSet 所设置的列
ew.sqlSelect 要select的列

 

包里边定义好的常量。我们可以直接用这些常量。

mybatis-plus-core-3.3.2.jar\com\baomidou\mybatisplus\core\toolkit\Constants.class

package com.baomidou.mybatisplus.core.toolkit;

public interface Constants extends StringPool {
    String MYBATIS_PLUS = "mybatis-plus";
    String MD5 = "MD5";
    String AES = "AES";
    String AES_CBC_CIPHER = "AES/CBC/PKCS5Padding";
    String ENTITY = "et";
    String ENTITY_DOT = "et.";
    String WRAPPER = "ew";
    String WRAPPER_DOT = "ew.";
    String WRAPPER_ENTITY = "ew.entity";
    String WRAPPER_SQLSEGMENT = "ew.sqlSegment";
    String WRAPPER_EMPTYOFNORMAL = "ew.emptyOfNormal";
    String WRAPPER_NONEMPTYOFNORMAL = "ew.nonEmptyOfNormal";
    String WRAPPER_NONEMPTYOFENTITY = "ew.nonEmptyOfEntity";
    String WRAPPER_EMPTYOFWHERE = "ew.emptyOfWhere";
    String WRAPPER_NONEMPTYOFWHERE = "ew.nonEmptyOfWhere";
    String WRAPPER_ENTITY_DOT = "ew.entity.";
    String U_WRAPPER_SQL_SET = "ew.sqlSet";
    String Q_WRAPPER_SQL_SELECT = "ew.sqlSelect";
    String Q_WRAPPER_SQL_COMMENT = "ew.sqlComment";
    String Q_WRAPPER_SQL_FIRST = "ew.sqlFirst";
    String COLUMN_MAP = "cm";
    String COLUMN_MAP_IS_EMPTY = "cm.isEmpty";
    String COLLECTION = "coll";
    String WHERE = "WHERE";
    String MP_OPTLOCK_INTERCEPTOR = "oli";
    String MP_OPTLOCK_VERSION_ORIGINAL = "MP_OPTLOCK_VERSION_ORIGINAL";
    String MP_OPTLOCK_VERSION_COLUMN = "MP_OPTLOCK_VERSION_COLUMN";
    String MP_OPTLOCK_ET_ORIGINAL = "MP_OPTLOCK_ET_ORIGINAL";
    String WRAPPER_PARAM = "MPGENVAL";
    String WRAPPER_PARAM_FORMAT = "#{%s.paramNameValuePairs.%s}";
}

实例

entity

package com.example.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;
import lombok.Data;

@Data
@TableName(value = "tb_user")//指定表名
public class User{
    //value与数据库主键列名一致,若实体类属性名与表主键列名一致可省略value
    @TableId(value = "id",type = IdType.ASSIGN_UUID)//指定自增策略
    private String id;
    private String name;

    //若没有开启驼峰命名,或者表中列名不符合驼峰规则,可通过该注解指定数据库表中的列名,exist标明数据表中有没有对应列
    @TableField(value = "last_name",exist = true)
    private String lastName;
    private String email;
    private Integer gender;
    private Integer age;
}

mapper

package com.example.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public interface UserMapper extends BaseMapper {
    @Select("select * from tb_user ${ew.customSqlSegment}")
    List testSelect1(@Param("ew") Wrapper wrapper);
//    List testSelect1(@Param(Constants.WRAPPER) Wrapper wrapper);

    @Select("select * from ${table_name} ${ew.customSqlSegment}")
    List testSelect2(@Param("table_name")String tableName, @Param("ew") Wrapper wrapper);

    @Select("select ${ew.SqlSelect} from ${table_name} ${ew.customSqlSegment}")
    List testSelect3(@Param("table_name")String tableName, @Param("ew") Wrapper wrapper);

    @Select("select ${ew.SqlSelect} from ${table_name} ${ew.customSqlSegment}")
    List> testSelect4(@Param("table_name")String tableName, @Param("ew") Wrapper wrapper);

    @Select("select * from ${table_name} where age = #{age}")
    List testSelect5(@Param("table_name")String tableName,  @Param("age")Integer age);

    @Select("select ${ew.SqlSelect} from ${table_name} where age = #{age} ${ew.customSqlSegment}")
    List testSelect6(@Param("table_name")String tableName,  @Param("age")Integer age,@Param("ew") Wrapper wrapper);

    @Select("select * from ${table_name} ${ew.customSqlSegment}")
    User testSelect7(@Param("table_name")String tableName,  @Param("ew") Wrapper wrapper);

    //只取name这一列
    @Select("SELECT tb_user.name FROM tb_user ${ew.customSqlSegment}")
    List getNames(@Param("ew") Wrapper wrapper);

    @Select("update ${table_name} set ${ew.sqlSet} ${ew.customSqlSegment}")
    int testUpdate1(@Param("table_name")String tableName, @Param("ew") Wrapper wrapper);
}

测试代码

package com.example;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.junit.jupiter.api.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;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
class CustomSqlTests {
    @Autowired
    UserMapper userMapper;

    @Test
    public void insert() {
        User user = new User();
        for (int i = 0; i < 10; i++) {
            user.setId(String.valueOf(i));
            user.setName("Iron Man" + i);
            if (i < 5) {
                user.setAge(20);
            } else {
                user.setAge(23);
            }
            userMapper.insert(user);
        }
    }

    @Test
    public void mySqlTest123() {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", "张三");
        queryWrapper.eq("age", 20);
        queryWrapper.eq("last_name", null);
        queryWrapper.select("id", "age");
//        List users = userMapper.testSelect1(queryWrapper);
//        List users = userMapper.testSelect2("tb_user", queryWrapper);
        List users = userMapper.testSelect3("tb_user", queryWrapper);

        users.forEach(System.out::println);
    }

    @Test
    public void mySqlTest4() {
        QueryWrapper queryWrapper = new QueryWrapper<>();

        queryWrapper.select("id", "age");
        List> mapList = userMapper.testSelect4("tb_user", queryWrapper);

        mapList.forEach(System.out::println);
    }

    @Test
    public void mySqlTest56() {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", "张三").eq("last_name", null);
        queryWrapper.select("id", "age");
//        List userList = userMapper.testSelect5("tb_user", 28);
        List userList = userMapper.testSelect6("tb_user", 28, queryWrapper);

        userList.forEach(System.out::println);
    }

    @Test
    public void mySqlTest7() {
        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("age", "20");
        queryWrapper.eq("name", "Iron Man1");
        User user = userMapper.testSelect7("tb_user", queryWrapper);

        System.out.println(user);
    }

    @Test
    public void getNames() {
        QueryWrapper objectQueryWrapper = new QueryWrapper<>()
                .eq("age", 20);
        List names = this.userMapper.getNames(objectQueryWrapper);
        System.out.println(names);
    }
}

mySqlTest123测试结果

testSelect1/ testSelect2结果

==>  Preparing: select * from tb_user WHERE (name = ? AND age = ? AND last_name = ?) 
==> Parameters: 张三(String), 28(Integer), null
<==      Total: 0

 testSelect3结果

==>  Preparing: select id,age from tb_user WHERE (name = ? AND age = ? AND last_name = ?) 
==> Parameters: 张三(String), 28(Integer), null
<==      Total: 0

mySqlTest4测试结果(成功:返回List>)

==>  Preparing: select id,age from tb_user 
==> Parameters: 
<==    Columns: id, age
<==        Row: 321eece6b1620ab97123785edbdef490, 20
<==        Row: 101eece6b1620ab97ffa8c8edbdef490, 20
<==        Row: 9d532cbadd8ea0beb7ea5a7c867bc863, 20
<==      Total: 3
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@43f9dd56]
{id=321eece6b1620ab97123785edbdef490, age=20}
{id=101eece6b1620ab97ffa8c8edbdef490, age=20}
{id=9d532cbadd8ea0beb7ea5a7c867bc863, age=20}

mySqlTest56测试结果

testSelect5(通过#{}传列的值)

==>  Preparing: select * from tb_user where age = ? 
==> Parameters: 28(Integer)
<==      Total: 0

 testSelect6(报错(既使用where又使用Wrapper))

==>  Preparing: select id,age from tb_user where age = ? WHERE (name = ? AND last_name = ?) 
==> Parameters: 28(Integer), 张三(String), null

mySqlTest7测试结果(只取一个。若返回只有一个则成功,否则报错)

返回1个赋值给1个(成功)

==>  Preparing: select * from tb_user WHERE (name = ?) 
==> Parameters: Iron Man1(String)
<==    Columns: id, name, last_name, email, gender, age
<==        Row: 1, Iron Man1, null, null, null, 20
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4ba6ec50]
User(id=1, name=Iron Man1, lastName=null, email=null, gender=null, age=20)

返回多个赋值给1个(失败

==>  Preparing: select * from tb_user WHERE (age = ?) 
==> Parameters: 20(String)
<==    Columns: id, name, last_name, email, gender, age
<==        Row: 321eece6b1620ab97123785edbdef490, null, 东方不败, [email protected], 1, 20
<==        Row: 101eece6b1620ab97ffa8c8edbdef490, null, Tony, [email protected], 1, 20
<==        Row: 9d532cbadd8ea0beb7ea5a7c867bc863, null, Pepper, [email protected], 2, 20
<==        Row: 0, Iron Man0, null, null, null, 20
<==        Row: 1, Iron Man1, null, null, null, 20
<==        Row: 2, Iron Man2, null, null, null, 20
<==        Row: 3, Iron Man3, null, null, null, 20
<==        Row: 4, Iron Man4, null, null, null, 20
<==      Total: 8
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@76464795]


org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 8

getNames测试结果

==>  Preparing: SELECT tb_user.name FROM tb_user WHERE (age = ?) 
==> Parameters: 20(Integer)
<==    Columns: name
<==        Row: Iron Man0
<==        Row: Iron Man1
<==        Row: Iron Man2
<==        Row: Iron Man3
<==        Row: Iron Man4
<==      Total: 5
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@59b65dce]
[Iron Man0, Iron Man1, Iron Man2, Iron Man3, Iron Man4]

多表查询/分页

其他网址

最简单的 MyBatis Plus 的多表联接、分页查询实现方法_IT小村-CSDN博客_mybatis plus多表查询
mybatis Plus 多表联合查询

Mybatis-Plus官网(分页)

源码

entity

@Data
@TableName("t_question")
public class Question implements Serializable {

    private static final long serialVersionUID = 1L;

    // 问答主键id
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    // 学生外键id
    @TableField("student_id")
    private Integer studentId;

    // 问题内容
    private String content;

    // 问题悬赏的积分
    private Integer value;
}

 

@Data
@TableName("t_student")
public class Student implements Serializable {

    private static final long serialVersionUID = 1L;

    // 学生主键id
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    // 学生名称
    private String name;

    // 学生积分数
    private Integer points;
}

VO

@Data
public class QuestionStudentVO implements Serializable {
    // 问答主键id
    private Integer id;

    // 学生外键id
    private Integer studentId;

    //学生名字
    private List name;

    //学生积分
    private Integer points;

    // 问题内容
    private String content;

    // 问题悬赏的积分
    private Integer value;
}

Mapper 

package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.Question;
import com.example.vo.QuestionStudentVO;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface QuestionMapper extends BaseMapper {
    @Select("SELECT t_question.*,t_student.`name`,t_student.points FROM t_question,t_student " +
            "WHERE t_question.student_id=t_student.id")
    List getQuestionStudent();

    @Select("SELECT t_question.*,t_student.`name` FROM t_question,t_student WHERE t_question.student_id=t_student.id")
    List getQuestionStudentPage (Page page);
}

分页插件 

@EnableTransactionManagement
@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {
    // 分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

Controller

@RestController
@RequestMapping("/common")
public class CommonController {
    @Autowired
    QuestionService questionService;

    @Autowired
    StudentService studentService;

    @GetMapping("/getAllQuestionWithStudent")
    public Map getAllQuestionWithStudent() {
        Map map = new HashMap<>();
        List questionStudent = questionService.getQuestionStudent();
        if (questionStudent.size() == 0) {
            map.put("code", 400);
        } else {
            map.put("code", 200);
            map.put("data", questionStudent);
        }
        return map;
    }

    @GetMapping("/getAllQuestionWithStudentByPage/{page}/{size}")
    public Map getAllQuestionWithStudentByPage(@PathVariable Integer page, @PathVariable Integer size) {
        Map map = new HashMap<>();
        Page questionStudent = questionService.getQuestionStudentPage (new Page<>(page, size));
        if (questionStudent.getRecords().size() == 0) {
            map.put("code", 400);
        } else {
            map.put("code", 200);
            map.put("data", questionStudent);
        }
        return map;
    }
}

sql

DROP TABLE IF EXISTS `t_question`;
CREATE TABLE `t_question` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `student_id` int(11) DEFAULT NULL,
  `content` varchar(64) DEFAULT NULL,
  `value` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1002 DEFAULT CHARSET=utf8;
 
 
BEGIN;
INSERT INTO `t_question` VALUES ('1001', '1', 'this is question content', '10');
COMMIT;
 
DROP TABLE IF EXISTS `t_student`;
CREATE TABLE `t_student` (
  `id` int(11) NOT NULL,
  `name` varchar(64) DEFAULT NULL,
  `points` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
BEGIN;
INSERT INTO `t_student` VALUES ('1', 'Iron Man', '201');
COMMIT;

多表查询测试

postman访问:http://localhost:8080/common/getAllQuestionWithStudent

后端结果

==>  Preparing: SELECT t_question.*,t_student.`name` FROM t_question,t_student WHERE t_question.student_id=t_student.id 
==> Parameters: 
<==    Columns: id, student_id, content, value, name
<==        Row: 1001, 1, this is question content, 10, Iron Man
<==      Total: 1

前端结果(可见,只能给Object赋值,不能给数组或list赋值)

{
    "code": 200,
    "data": [
        {
            "id": 1001,
            "studentId": 1,
            "name": null,
            "points": 201,
            "content": "this is question content",
            "value": 10
        }
    ]
}

分页测试

postman访问:http://localhost:8080/common/getAllQuestionWithStudentByPage/1/2

后端结果

==>  Preparing: SELECT COUNT(1) FROM t_question, t_student WHERE t_question.student_id = t_student.id 
==> Parameters: 
<==    Columns: COUNT(1)
<==        Row: 1
==>  Preparing: SELECT t_question.*,t_student.`name` FROM t_question,t_student WHERE t_question.student_id=t_student.id LIMIT ?,? 
==> Parameters: 0(Long), 2(Long)
<==    Columns: id, student_id, content, value, name
<==        Row: 1001, 1, this is question content, 10, Iron Man
<==      Total: 1

前端结果

{
    "code": 200,
    "data": {
        "records": [
            {
                "id": 1001,
                "studentId": 1,
                "name": "Iron Man",
                "content": "this is question content",
                "value": 10
            }
        ],
        "total": 1,
        "size": 2,
        "current": 1,
        "orders": [],
        "optimizeCountSql": true,
        "hitCount": false,
        "searchCount": true,
        "pages": 1
    }
}

 

你可能感兴趣的:(Mybatis-Plus系列--进阶实例)