MyBatis-Plus多表聯(lián)查(動(dòng)態(tài)查詢)的項(xiàng)目實(shí)踐
簡(jiǎn)介
本文用示例介紹使用MyBatis-Plus進(jìn)行多表查詢的方法,包括靜態(tài)查詢和動(dòng)態(tài)查詢。
代碼
controller
package com.example.demo.business.blog.controller;
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.example.demo.business.blog.mapper.BlogMapper;
import com.example.demo.business.blog.vo.BlogVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "自定義SQL")
@RestController
@RequestMapping("/blog")
public class BlogController {
@Autowired
private BlogMapper blogMapper;
@ApiOperation("靜態(tài)查詢")
@GetMapping("staticQuery")
public String staticQuery() {
return blogMapper.findUserNameByBlogId(1L);
}
@ApiOperation("動(dòng)態(tài)查詢")
@GetMapping("dynamicQuery")
public IPage<BlogVO> dynamicQuery(Page<BlogVO> page, String nickName, String title) {
QueryWrapper<BlogVO> queryWrapper = new QueryWrapper<>();
queryWrapper.like(StringUtils.hasText(nickName), "t_user.nick_name", nickName);
queryWrapper.like(StringUtils.hasText(title), "t_blog.title", title);
queryWrapper.eq("t_blog.deleted_flag", 0);
queryWrapper.eq("t_user.deleted_flag", 0);
queryWrapper.apply("t_blog.user_id = t_user.id");
return blogMapper.findBlog(page, queryWrapper);
}
}Mapper
package com.example.demo.business.blog.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.demo.business.blog.entity.Blog;
import com.example.demo.business.blog.vo.BlogVO;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface BlogMapper extends BaseMapper<Blog> {
/**
* 靜態(tài)查詢
*/
@Select("SELECT t_user.user_name " +
" FROM t_blog, t_user " +
" WHERE t_blog.id = #{id} " +
" AND t_blog.user_id = t_user.id")
String findUserNameByBlogId(@Param("id") Long id);
/**
* 動(dòng)態(tài)查詢
*/
@Select("SELECT * " +
" FROM t_blog, t_user " +
" ${ew.customSqlSegment} ")
IPage<BlogVO> findBlog(IPage<BlogVO> page, @Param("ew") Wrapper wrapper);
}VO
package com.example.demo.business.blog.vo;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class BlogVO {
private Long id;
private Long userId;
private String userName;
/**
* 標(biāo)題
*/
private String title;
/**
* 摘要
*/
private String description;
/**
* 內(nèi)容
*/
private String content;
/**
* 創(chuàng)建時(shí)間
*/
private LocalDateTime createTime;
/**
* 修改時(shí)間
*/
private LocalDateTime updateTime;
/**
* 昵稱(這個(gè)是t_user的字段)
*/
private String nickName;
}建庫(kù)建表
DROP DATABASE IF EXISTS mp;
CREATE DATABASE mp DEFAULT CHARACTER SET utf8;
USE mp;
DROP TABLE IF EXISTS `t_user`;
DROP TABLE IF EXISTS `t_blog`;
SET NAMES utf8mb4;
CREATE TABLE `t_user`
(
`id` BIGINT(0) NOT NULL AUTO_INCREMENT,
`user_name` VARCHAR(64) NOT NULL COMMENT '用戶名(不能重復(fù))',
`nick_name` VARCHAR(64) NOT NULL COMMENT '昵稱(可以重復(fù))',
`email` VARCHAR(64) COMMENT '郵箱',
`create_time` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時(shí)間',
`update_time` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時(shí)間',
`deleted_flag` BIGINT(0) NOT NULL DEFAULT 0 COMMENT '0:未刪除 其他:已刪除',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `index_user_name_deleted_flag`(`user_name`, `deleted_flag`),
KEY `index_create_time`(`create_time`)
) ENGINE = InnoDB COMMENT = '用戶';
CREATE TABLE `t_blog`
(
`id` BIGINT(0) NOT NULL AUTO_INCREMENT,
`user_id` BIGINT(0) NOT NULL,
`user_name` VARCHAR(64) NOT NULL,
`title` VARCHAR(256) CHARACTER SET utf8mb4 NOT NULL COMMENT '標(biāo)題',
`description` VARCHAR(256) CHARACTER SET utf8mb4 NOT NULL COMMENT '摘要',
`content` LONGTEXT CHARACTER SET utf8mb4 NOT NULL COMMENT '內(nèi)容',
`create_time` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時(shí)間',
`update_time` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時(shí)間',
`deleted_flag` BIGINT(0) NOT NULL DEFAULT 0 COMMENT '0:未刪除 其他:已刪除',
PRIMARY KEY (`id`) USING BTREE,
KEY `index_user_id`(`user_id`),
KEY `index_create_time`(`create_time`)
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COMMENT = '博客';
INSERT INTO `t_user` VALUES (1, 'knife', '刀刃', 'abc@qq.com', '2021-01-23 09:33:36', '2021-01-23 09:33:36', 0);
INSERT INTO `t_user` VALUES (2, 'sky', '天藍(lán)', '123@qq.com', '2021-01-24 18:12:21', '2021-01-24 18:12:21', 0);
INSERT INTO `t_blog` VALUES (1, 1, 'knife', 'Java中枚舉的用法',
'本文介紹Java的枚舉類的使用',
'本文介紹Java的枚舉類的使用',
'2021-01-23 11:33:36', '2021-01-23 11:33:36', 0);
INSERT INTO `t_blog` VALUES (2, 1, 'knife', 'Java中泛型的用法',
'本文介紹Java的泛型的使用。',
'本文介紹Java的泛型的使用。',
'2021-01-28 23:37:37', '2021-01-28 23:37:37', 0);
INSERT INTO `t_blog` VALUES (3, 1, 'knife', 'Java的HashMap的原理',
'本文介紹Java的HashMap的原理。',
'本文介紹Java的HashMap的原理。',
'2021-05-28 09:06:06', '2021-05-28 09:06:06', 0);
INSERT INTO `t_blog` VALUES (4, 1, 'knife', 'Java中BigDecimal的用法',
'本文介紹Java的BigDecimal的使用。',
'本文介紹Java的BigDecimal的使用。',
'2021-06-24 20:36:54', '2021-06-24 20:36:54', 0);
INSERT INTO `t_blog` VALUES (5, 1, 'knife', 'Java中反射的用法',
'本文介紹Java的反射的使用。',
'本文介紹Java的反射的使用。',
'2021-10-28 22:24:18', '2021-10-28 22:24:18', 0);
INSERT INTO `t_blog` VALUES (6, 2, 'sky', 'Vue-cli的使用',
'Vue-cli是Vue的一個(gè)腳手架工具',
'Vue-cli可以用來(lái)創(chuàng)建vue項(xiàng)目',
'2021-02-23 11:34:36', '2021-02-25 14:33:36', 0);
INSERT INTO `t_blog` VALUES (7, 2, 'sky', 'Vuex的用法',
'Vuex是vue用于共享變量的插件',
'一般使用vuex來(lái)共享變量',
'2021-03-28 23:37:37', '2021-03-28 23:37:37', 0);配置
application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/mp?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
password: 222333
username: root
#mybatis-plus配置控制臺(tái)打印完整帶參數(shù)SQL語(yǔ)句
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImplMyBatis-Plus分頁(yè)插件配置
package com.example.demo.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
@Configuration
public class MyBatisPlusConfig {
/**
* 分頁(yè)插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}依賴
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.example</groupId>
<artifactId>MyBatis-Plus_Multiple</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MyBatis-Plus_Multiple</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.12.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-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<!-- 指定maven編譯的jdk版本。若不指定,maven3默認(rèn)用jdk 1.5 maven2默認(rèn)用jdk1.3 -->
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>測(cè)試
訪問(wèn)knife4j頁(yè)面:http://localhost:8080/doc.html

1.靜態(tài)查詢

2.動(dòng)態(tài)查詢
1.不傳條件

結(jié)果:(可以查到所有數(shù)據(jù))

后端輸出
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@60bbb9ec] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1853643659 wrapping com.mysql.cj.jdbc.ConnectionImpl@6a43d29c] will not be managed by Spring
==> Preparing: SELECT COUNT(*) AS total FROM t_blog, t_user WHERE (t_blog.deleted_flag = ? AND t_user.deleted_flag = ? AND t_blog.user_id = t_user.id)
==> Parameters: 0(Integer), 0(Integer)
<== Columns: total
<== Row: 7
<== Total: 1
==> Preparing: SELECT * FROM t_blog, t_user WHERE (t_blog.deleted_flag = ? AND t_user.deleted_flag = ? AND t_blog.user_id = t_user.id) LIMIT ?
==> Parameters: 0(Integer), 0(Integer), 10(Long)
<== Columns: id, user_id, user_name, title, description, content, create_time, update_time, deleted_flag, id, user_name, nick_name, email, create_time, update_time, deleted_flag
<== Row: 1, 1, knife, Java中枚舉的用法, 本文介紹Java的枚舉類的使用, <<BLOB>>, 2021-01-23 11:33:36, 2021-01-23 11:33:36, 0, 1, knife, 刀刃, abc@qq.com, 2021-01-23 09:33:36, 2021-01-23 09:33:36, 0
<== Row: 2, 1, knife, Java中泛型的用法, 本文介紹Java的泛型的使用。, <<BLOB>>, 2021-01-28 23:37:37, 2021-01-28 23:37:37, 0, 1, knife, 刀刃, abc@qq.com, 2021-01-23 09:33:36, 2021-01-23 09:33:36, 0
<== Row: 3, 1, knife, Java的HashMap的原理, 本文介紹Java的HashMap的原理。, <<BLOB>>, 2021-05-28 09:06:06, 2021-05-28 09:06:06, 0, 1, knife, 刀刃, abc@qq.com, 2021-01-23 09:33:36, 2021-01-23 09:33:36, 0
<== Row: 4, 1, knife, Java中BigDecimal的用法, 本文介紹Java的BigDecimal的使用。, <<BLOB>>, 2021-06-24 20:36:54, 2021-06-24 20:36:54, 0, 1, knife, 刀刃, abc@qq.com, 2021-01-23 09:33:36, 2021-01-23 09:33:36, 0
<== Row: 5, 1, knife, Java中反射的用法, 本文介紹Java的反射的使用。, <<BLOB>>, 2021-10-28 22:24:18, 2021-10-28 22:24:18, 0, 1, knife, 刀刃, abc@qq.com, 2021-01-23 09:33:36, 2021-01-23 09:33:36, 0
<== Row: 6, 2, sky, Vue-cli的使用, Vue-cli是Vue的一個(gè)腳手架工具, <<BLOB>>, 2021-02-23 11:34:36, 2021-02-25 14:33:36, 0, 2, sky, 天藍(lán), 123@qq.com, 2021-01-24 18:12:21, 2021-01-24 18:12:21, 0
<== Row: 7, 2, sky, Vuex的用法, Vuex是vue用于共享變量的插件, <<BLOB>>, 2021-03-28 23:37:37, 2021-03-28 23:37:37, 0, 2, sky, 天藍(lán), 123@qq.com, 2021-01-24 18:12:21, 2021-01-24 18:12:21, 0
<== Total: 7
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@60bbb9ec]
2.傳條件
只傳:nickName:刀

結(jié)果

后端結(jié)果
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@30026aab] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@2127441980 wrapping com.mysql.cj.jdbc.ConnectionImpl@6a43d29c] will not be managed by Spring
==> Preparing: SELECT COUNT(*) AS total FROM t_blog, t_user WHERE (t_user.nick_name LIKE ? AND t_blog.deleted_flag = ? AND t_user.deleted_flag = ? AND t_blog.user_id = t_user.id)
==> Parameters: %刀%(String), 0(Integer), 0(Integer)
<== Columns: total
<== Row: 5
<== Total: 1
==> Preparing: SELECT * FROM t_blog, t_user WHERE (t_user.nick_name LIKE ? AND t_blog.deleted_flag = ? AND t_user.deleted_flag = ? AND t_blog.user_id = t_user.id) LIMIT ?
==> Parameters: %刀%(String), 0(Integer), 0(Integer), 10(Long)
<== Columns: id, user_id, user_name, title, description, content, create_time, update_time, deleted_flag, id, user_name, nick_name, email, create_time, update_time, deleted_flag
<== Row: 1, 1, knife, Java中枚舉的用法, 本文介紹Java的枚舉類的使用, <<BLOB>>, 2021-01-23 11:33:36, 2021-01-23 11:33:36, 0, 1, knife, 刀刃, abc@qq.com, 2021-01-23 09:33:36, 2021-01-23 09:33:36, 0
<== Row: 2, 1, knife, Java中泛型的用法, 本文介紹Java的泛型的使用。, <<BLOB>>, 2021-01-28 23:37:37, 2021-01-28 23:37:37, 0, 1, knife, 刀刃, abc@qq.com, 2021-01-23 09:33:36, 2021-01-23 09:33:36, 0
<== Row: 3, 1, knife, Java的HashMap的原理, 本文介紹Java的HashMap的原理。, <<BLOB>>, 2021-05-28 09:06:06, 2021-05-28 09:06:06, 0, 1, knife, 刀刃, abc@qq.com, 2021-01-23 09:33:36, 2021-01-23 09:33:36, 0
<== Row: 4, 1, knife, Java中BigDecimal的用法, 本文介紹Java的BigDecimal的使用。, <<BLOB>>, 2021-06-24 20:36:54, 2021-06-24 20:36:54, 0, 1, knife, 刀刃, abc@qq.com, 2021-01-23 09:33:36, 2021-01-23 09:33:36, 0
<== Row: 5, 1, knife, Java中反射的用法, 本文介紹Java的反射的使用。, <<BLOB>>, 2021-10-28 22:24:18, 2021-10-28 22:24:18, 0, 1, knife, 刀刃, abc@qq.com, 2021-01-23 09:33:36, 2021-01-23 09:33:36, 0
<== Total: 5
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@30026aab]
到此這篇關(guān)于MyBatis-Plus多表聯(lián)查(動(dòng)態(tài)查詢)的項(xiàng)目實(shí)踐的文章就介紹到這了,更多相關(guān)MyBatis-Plus多表聯(lián)查內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- mybatis plus動(dòng)態(tài)數(shù)據(jù)源切換及查詢過(guò)程淺析
- MybatisPlus實(shí)現(xiàn)分頁(yè)查詢和動(dòng)態(tài)SQL查詢的示例代碼
- MyBatis-Plus多表聯(lián)查的實(shí)現(xiàn)方法(動(dòng)態(tài)查詢和靜態(tài)查詢)
- Mybatis-plus動(dòng)態(tài)條件查詢QueryWrapper的使用案例
- MybatisPlus使用Mybatis的XML的動(dòng)態(tài)SQL的功能實(shí)現(xiàn)多表查詢
- mybatis-plus @select動(dòng)態(tài)查詢方式
- mybatis-plus?實(shí)現(xiàn)查詢表名動(dòng)態(tài)修改的示例代碼
相關(guān)文章
spring boot微服務(wù)自定義starter原理詳解
這篇文章主要介紹了spring boot微服務(wù)自定義starter原理詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
Nacos docker單機(jī)模式部署實(shí)現(xiàn)過(guò)程詳解
這篇文章主要介紹了Nacos docker單機(jī)模式部署實(shí)現(xiàn)過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
解決java文件流處理異常 mark/reset not supported問(wèn)題
這篇文章主要介紹了解決java文件流處理異常 mark/reset not supported問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10
Spring Bean 依賴注入常見(jiàn)錯(cuò)誤問(wèn)題
這篇文章主要介紹了Spring Bean 依賴注入常見(jiàn)錯(cuò)誤問(wèn)題,文中提到value的工作大體分為三個(gè)核心步驟,具體內(nèi)容詳情跟隨小編一起看看吧2021-09-09
Spring AOP之@Around,@AfterReturning使用、切不進(jìn)去的解決方案
這篇文章主要介紹了Spring AOP之@Around,@AfterReturning使用、切不進(jìn)去的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
解決springboot中mongodb不啟動(dòng)及Dao不能被掃描到的問(wèn)題
這篇文章主要介紹了解決springboot中mongodb不啟動(dòng)及Dao不能被掃描到的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05

