Bootstrap

MyBatis-Plus-Join的基本使用方法,一些常用示例。告别繁杂的SQL

概要

` 【java程序员】主要记录下新手使用MPJ,大大减少mybatis.xml里面的乱七八糟的sql

这里是mpj官网

环境准备

maven依赖

		<properties>
	        <java.version>8</java.version>
	        <mysql-connector-java.version>8.0.28</mysql-connector-java.version>		
			<mybatis-plus.version>3.5.5</mybatis-plus.version>
	        <myBatis-plus-join.version>1.4.5</myBatis-plus-join.version>
		</properties>
        
        <dependencies>
             <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql-connector-java.version}</version>
                <scope>runtime</scope>
            </dependency>
        	<dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>${mybatis-plus.version}</version>
            </dependency>
            <dependency>
                <groupId>com.github.yulichang</groupId>
                <artifactId>mybatis-plus-join</artifactId>
                <version>${myBatis-plus-join.version}</version>
            </dependency>
        </dependencies>

下面是三张示例表

-- 创建用户表
CREATE TABLE `mpj_user` (
  `id` bigint(20) NOT NULL,
  `account` varchar(20) DEFAULT NULL COMMENT '账号',
  `password` varchar(255) DEFAULT NULL COMMENT '密码',
  `salt` varchar(50) DEFAULT NULL COMMENT '盐',
  `name` varchar(50) DEFAULT NULL COMMENT '名称',
  `phone` varchar(20) DEFAULT NULL COMMENT '联系电话',
  `create_datetime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '数据创建时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='mpj示例用户表';

-- 创建文章表
CREATE TABLE `mpj_article` (
  `id` bigint(20) NOT NULL,
  `title` varchar(255) DEFAULT NULL COMMENT '文章标题',
  `content` text COMMENT '文章内容',
  `author` bigint(20) DEFAULT NULL COMMENT '作者',
  `create_datetime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `publish_status` int(2) DEFAULT NULL COMMENT '发布状态,0草稿,1已发布',
  `publish_datetime` datetime DEFAULT NULL COMMENT '发布时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='mpj示例文章表';

-- 创建收藏表
CREATE TABLE `mpj_article_collect` (
  `id` bigint(20) NOT NULL,
  `article_id` bigint(20) DEFAULT NULL COMMENT '文章id',
  `user_id` bigint(20) DEFAULT NULL COMMENT '用户id',
  `create_datetime` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '收藏时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='mpj示例文章收藏表';

然后生成一些测试数据

package com.example.demo;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.example.demo.mpj.entity.MpjArticle;
import com.example.demo.mpj.entity.MpjArticleCollect;
import com.example.demo.mpj.entity.MpjUser;
import com.example.demo.mpj.service.MpjArticleCollectService;
import com.example.demo.mpj.service.MpjArticleService;
import com.example.demo.mpj.service.MpjUserService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
@SpringBootTest
class DemoApplicationTests {
    @Resource
    private MpjUserService mpjUserService;
    @Resource
    private MpjArticleService mpjArticleService;
    @Resource
    private MpjArticleCollectService mpjArticleCollectService;

    /**
     * 生成一些用户
     */
    @Test
    public void generateUser(){
        MpjUser mpjUser = new MpjUser();
        mpjUser.setAccount("zhangsan");
        mpjUser.setName("张三");
        mpjUser.setPhone("13838383838");
        MpjUser mpjUser1 = new MpjUser();
        mpjUser1.setAccount("lisi");
        mpjUser1.setName("李四");
        mpjUser1.setPhone("13938383838");
        MpjUser mpjUser2 = new MpjUser();
        mpjUser2.setAccount("wangwu");
        mpjUser2.setName("王五");
        mpjUser2.setPhone("13738383838");
        MpjUser mpjUser3 = new MpjUser();
        mpjUser3.setAccount("zhaoliu");
        mpjUser3.setName("赵六");
        mpjUser3.setPhone("13638383838");
        MpjUser mpjUser4 = new MpjUser();
        mpjUser4.setAccount("sunqi");
        mpjUser4.setName("孙七");
        mpjUser4.setPhone("13538383838");

        List<MpjUser> userList = new ArrayList<>();
        userList.add(mpjUser);
        userList.add(mpjUser1);
        userList.add(mpjUser2);
        userList.add(mpjUser3);
        userList.add(mpjUser4);
        mpjUserService.saveBatch(userList);
    }

    /**
     * 生成文章 以及收藏关系
     */
    @Test
    public void generateArticle(){
        List<Long> collect = mpjUserService.list().stream().map(MpjUser::getId).collect(Collectors.toList());
        int size = collect.size();
        int count = 5000;
        int q = 1;
        List<MpjArticle> articleList = new ArrayList<>();
        while (count-- > 0){
            MpjArticle article = new MpjArticle();
            article.setAuthor(collect.get(RandomUtil.randomInt(0, size)));
            article.setTitle("这是文章" + q++);
            article.setContent("内容");
            article.setCreateDatetime(new Date());
            article.setPublishStatus(RandomUtil.randomInt(0,2));
            article.setPublishDatetime(new Date());
            articleList.add(article);
        }
        mpjArticleService.saveBatch(articleList);
        //生成时间
        List<DateTime> dateTimes = DateUtil.rangeToList(DateUtil.parseDate("2024-02-04"), DateUtil.parseDateTime("2024-02-05 23:59:59"), DateField.SECOND);

        AtomicInteger ai = new AtomicInteger(0);
        List<MpjArticleCollect> list = new ArrayList<>();
        //分配一下收藏情况
        articleList.forEach(a -> {
            int i = RandomUtil.randomInt(1, 4);
            Map<Integer, Integer> map = new HashMap<>();
            //需要删除的
            for(int k = 0; k < i; k ++){
                int i1 = RandomUtil.randomInt(0, size);
                map.put(i1, i1);
            }
            for(int k = 0; k < collect.size(); k++){
                if(!map.containsKey(k)){
                    MpjArticleCollect ac = new MpjArticleCollect();
                    ac.setArticleId(a.getId());
                    ac.setUserId(collect.get(k));
                    ac.setCreateDatetime(dateTimes.get(ai.getAndIncrement()));
                    list.add(ac);
                }
            }
        });
        mpjArticleCollectService.saveBatch(list);
    }
}


模拟生产环境查询

1、单条件关联联表查询
查询张三发布的文章

	/**
     * 单条件联表查询
     * 查询某个用户 发表的文章
     */
    @Test
    public void testQueryByAuthor(){
        MPJLambdaWrapper<MpjArticle> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAsClass(MpjArticle.class, MpjArticleVO.class)
                .selectAs(MpjUser::getName, MpjArticleVO::getAuthorName)
                .leftJoin(MpjUser.class, MpjUser::getId, MpjArticle::getAuthor)
                .eq(MpjUser::getName, "张三");

        Page<MpjArticleVO> mpjArticleVOPage = this.mpjArticleService.selectJoinListPage(new Page<>(1, 10), MpjArticleVO.class, wrapper);
        log.info("结果是{}", JSON.toJSONString(mpjArticleVOPage));
    }

2.子查询
查询张三发布的文章以及对应的收藏次数

	/**
     * 查询文章列表以及相应的收藏次数
     */
    @Test
    public void testQueryCollectTimes(){
        MPJLambdaWrapper<MpjArticle> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAsClass(MpjArticle.class, MpjArticleVO.class)
                .selectAs(MpjUser::getName, MpjArticleVO::getAuthorName)
                //从收藏表找到收藏条数
                .selectSub(MpjArticleCollect.class
                        , w -> w.selectCount(MpjArticleCollect::getId).eq(MpjArticleCollect::getArticleId, MpjArticle::getId)
                        , MpjArticleVO::getCollectTimes)
                .leftJoin(MpjUser.class, MpjUser::getId, MpjArticle::getAuthor)
                .eq(MpjUser::getName, "张三");

        Page<MpjArticleVO> mpjArticleVOPage = this.mpjArticleService.selectJoinListPage(new Page<>(1, 10), MpjArticleVO.class, wrapper);
        log.info("结果是{}", JSON.toJSONString(mpjArticleVOPage));
    }
;