MyBatis-Plus Conditional Constructor and Multi-Table Association Query

MyBatis-Plus conditional constructor and multi-table query

1. QueryWrapper Conditional Constructor

Prepare the data sheet:

Write a test case:

[Example 1]: Query the data of users whose name is not empty in the User data table, and whose mailbox is not empty, and whose age is greater than or equal to 25;

@Test
public void wrapperSelect1(){
    
    
    //查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于25
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper
        .isNotNull("name")
        .isNotNull("email")
        .ge("age", 25);
    List<User> users = userMapper.selectList(wrapper);
    users.forEach(System.out::println);
}

[Example 2]: Query user data whose age is 22;

@Test
public void wrapperSelect2(){
    
    
    //查询年龄是22的用户数据
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("age","22");
    List<User> users = userMapper.selectList(wrapper);
    System.out.println(users);
}

[Example 3]: Query the user data between the ages of 20-25 in the data table;

@Test
public void wrapperSelect3(){
    
    
    //查询年龄在20-25岁之间的用户
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.between("age",20,30);  //区间
    Integer count = userMapper.selectCount(wrapper);
    System.out.println(count);
}

<img src="C:\Users\17209\AppData\Roaming\Typora\typora-user-images\image-20220223144547320.png" alt="image-20220223144547320" style="zoom:80%;" /

[Example 4]: Query data records whose name does not contain "o" and whose email ends with "com";

@Test
public void wrapperSelect4(){
    
    
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper
        .notLike("name","o")
        .likeLeft("email","com");
    List<User> users = userMapper.selectList(wrapper);
    users.forEach(System.out::println);
}

[Example 5]: inSql subquery to find data records;

@Test
public void wrapperSelect5(){
    
    
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    // id 在子查询中查出来
    wrapper.inSql("id","select id from user where id < 4");
    List<Map<String, Object>> list = userMapper.selectMaps(wrapper);
    list.forEach(System.out::println);
}

[Example 6]: Sort data by age;

@Test
public void wrapperSelect6(){
    
    
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    //通过age进行排序
    wrapper.orderByAsc("age");
    List<User> users = userMapper.selectList(wrapper);
    users.forEach(System.out::println);
}

For the usage of the conditional constructor of MyBatis-Plus, please refer to the official website: https://baomidou.com/pages/10c804/


2. Multi-table association query

The content introduced above is all about adding, deleting, modifying and querying data in a single table. How to customize SQL and write interfaces for different query services? The multi-table association query is used here. We first prepared the following two data tables.

1. Write a POJO that maps the result set;

package com.trainingl.entity;

import lombok.Data;
// 映射结果集的实体类
@Data
public class OrderVO {
    
    
    private Integer pid;
    private String productName;
    private Integer count;
    private Integer uid;
    private String userName;
}

2. Custom interfaces and SQL statements in the mapper persistence interface;

package com.trainingl.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.trainingl.entity.OrderVO;
import com.trainingl.entity.User;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserMapper extends BaseMapper<User> {
    
    
	//自定义接口
    @Select("select p.*, u.name userName from product p,user u where u.id = p.uid and u.id = #{id}")
    List<OrderVO> SelectUerPro(Integer id);  //传入用户id
}

3. Test interface

@Test
public void test1(){
    
    
    //根据用户的id查询该用户购买的商品
    List<OrderVO> orderVOS = userMapper.SelectUerPro( 1);
    for (OrderVO orderVO : orderVOS) {
    
    
        System.out.println(orderVO);
    }
}


3. Performance analysis plugin (expanded understanding)

The function of the performance analysis component is to output each SQL statement and its execution time . This function depends on the p6spycomponent and supports MyBatis-Plus version 3.1.0 and above.

1. Introduce p6spy dependency in pom.xml;

<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
    <version>3.9.1</version>
</dependency>

2, application.yml placement;

spring:
  datasource:
    # driver-class-name 为 p6spy 提供的驱动类 
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    # url 前缀为 jdbc:p6spy 跟着冒号为对应数据库连接地址
    url: jdbc:p6spy:mysql://localhost/user?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    ...

3. Add the spy.properties configuration under the resources file;

#MP 3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2

When the console prints the log, it outputs the execution time and current time of the currently executed SQL statement;

This plug-in has performance loss and is not recommended for production environments. It is only used in test environments.

Guess you like

Origin blog.csdn.net/qq_41775769/article/details/123092194