SpringBoot中整合MyBatis-Plus-Join使用聯(lián)表查詢的實(shí)現(xiàn)
1、mybatis-plus
相信大家在日常的開發(fā)中用的最多的就是 mybatis-plus了吧,作為一個(gè) MyBatis (opens new window)的增強(qiáng)工具,在 MyBatis 的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開發(fā)、提高效率而生。文檔地址:https://baomidou.com/pages/24112f/
2、mybatis-plus-join
聯(lián)表查詢一直是 mybatis-plus 的短板之處,當(dāng)需要聯(lián)表查詢時(shí),還得打開 xml 文件寫入長(zhǎng)長(zhǎng)的 sql 語(yǔ)句。于是有需求就有產(chǎn)出,mybatis-plus-join 出世了,可以以類似 mybatis-plus 中 QueryWrapper 的方式來(lái)進(jìn)行聯(lián)表查詢,下面一起來(lái)體驗(yàn)吧!
3、引入依賴
<!-- mybatis-plus-join --> <dependency> <groupId>com.github.yulichang</groupId> <artifactId>mybatis-plus-join</artifactId> <version>1.2.4</version> </dependency> <!-- mybatis-plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.1</version> </dependency> <!-- mysql連接 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
4、mybatis配置信息
配置文件信息
spring: ? # 數(shù)據(jù)源配置 ? datasource: ? ? # 連接池類型 ? ? type: com.zaxxer.hikari.HikariDataSource ? ? driver-class-name: com.mysql.cj.jdbc.Driver ? ? # 數(shù)據(jù)庫(kù)名稱 ? ? database: test ? ? port: 3306 ? ? url: jdbc:mysql://127.0.0.1:${spring.datasource.port}/${spring.datasource.database}?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&useSSL=true&characterEncoding=UTF-8 ? ? username: root ? ? password: 123456 # mybatis配置 mybatis-plus: ? # xml文件路徑 ? mapper-locations: classpath*:/mapper/*.xml ? # 實(shí)體類路徑 ? type-aliases-package: com.asurplus.entity ? configuration: ? ? # 駝峰轉(zhuǎn)換 ? ? map-underscore-to-camel-case: true ? ? # 是否開啟緩存 ? ? cache-enabled: false ? ? # 打印sql,正式環(huán)境關(guān)閉 ? ? log-impl: org.apache.ibatis.logging.stdout.StdOutImpl ? # 全局配置 ? global-config: ? ? db-config: ? ? ? #主鍵類型 ?0:"數(shù)據(jù)庫(kù)ID自增",1:"該類型為未設(shè)置主鍵類型", 2:"用戶輸入ID",3:"全局唯一ID (數(shù)字類型唯一ID)", 4:"全局唯一ID UUID",5:"字符串全局唯一ID (idWorker 的字符串表示)"; ? ? ? id-type: AUTO
配置類信息
import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** ?* mybatisplus配置類 ?* ?* @author asurplus ?*/ @Configuration @MapperScan("com.asurplus.mapper") public class MybatisPlusConfigurer { ? ? @Bean ? ? public MybatisPlusInterceptor mybatisPlusInterceptor() { ? ? ? ? MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); ? ? ? ? interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); ? ? ? ? return interceptor; ? ? } }
5、建庫(kù)建表
建庫(kù)
CREATE DATABASE IF NOT EXISTS `test` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
建表
1、user 表
CREATE TABLE `user` ( `id` bigint(20) NOT NULL, `name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `sex` int(1) NULL DEFAULT NULL, `age` int(4) NULL DEFAULT NULL, `role_id` bigint(20) NULL DEFAULT NULL, `del_flag` int(3) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
2、role表
CREATE TABLE `role` ( `id` bigint(20) NOT NULL, `name` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `del_flag` int(3) NULL DEFAULT 0, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
3、插入數(shù)據(jù)
INSERT INTO `role` VALUES (1, '超級(jí)管理員', 0); INSERT INTO `user` VALUES (1, 'Asurplus', 1, 18, 1, 0);
6、代碼自動(dòng)生成
User
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.extension.activerecord.Model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = false) @TableName("user") @ApiModel(value="User對(duì)象", description="") public class User extends Model<User> { ? ? @TableId("id") ? ? private Long id; ? ? @TableField("name") ? ? private String name; ? ? @TableField("sex") ? ? private Integer sex; ? ? @TableField("age") ? ? private Integer age; ? ? @TableField("role_id") ? ? private Long roleId; ? ? @ApiModelProperty(value = "刪除狀態(tài)(0--未刪除1--已刪除)") ? ? @TableField("del_flag") ? ? @TableLogic ? ? private Integer delFlag; }
UserMapper
import com.asurplus.entity.User; import com.github.yulichang.base.MPJBaseMapper; public interface UserMapper extends MPJBaseMapper<User> { }
注意:這里我們繼承了 MPJBaseMapper
UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.asurplus.mapper.UserMapper"> </mapper>
UserService
import com.asurplus.entity.User; import com.github.yulichang.base.MPJBaseService; public interface UserService extends MPJBaseService<User> { }
注意:這里我們繼承了 MPJBaseService
UserServiceImpl import com.asurplus.entity.User; import com.asurplus.mapper.UserMapper; import com.asurplus.service.UserService; import com.github.yulichang.base.MPJBaseServiceImpl; import org.springframework.stereotype.Service; /** ?* <p> ?* 服務(wù)實(shí)現(xiàn)類 ?* </p> ?* ?* @author lizhou ?* @since 2022-12-14 ?*/ @Service public class UserServiceImpl extends MPJBaseServiceImpl<UserMapper, User> implements UserService { }
注意:這里我們繼承了 MPJBaseServiceImpl
7、聯(lián)表查詢
vo類
import com.asurplus.entity.User; import lombok.Data; @Data public class UserVO extends User { ? ? private String roleName; }
聯(lián)表查詢
public UserVO getUserVO(Long id) { UserVO userVO = this.baseMapper.selectJoinOne( UserVO.class, new MPJLambdaWrapper<User>() .selectAll(User.class) .selectAs(Role::getName, UserVO::getRoleName) .leftJoin(Role.class, Role::getId, User::getRoleId) .eq(User::getId, id)); return userVO; }
生成SQL:
SELECT t.id, t.NAME, t.sex, t.age, t.role_id, t.del_flag, t1.NAME AS roleName FROM USER t LEFT JOIN role t1 ON ( t1.id = t.role_id ) WHERE t.del_flag = 0 AND ( t.id = ? )
聯(lián)表分頁(yè)查詢
public IPage<UserVO> getUserVO(Long id) { IPage<UserVO> list = this.baseMapper.selectJoinPage( new Page<UserVO>(1, 10), UserVO.class, new MPJLambdaWrapper<User>() .selectAll(User.class) .selectAs(Role::getName, UserVO::getRoleName) .leftJoin(Role.class, Role::getId, User::getRoleId) .eq(User::getId, id)); return list; }
生成SQL:
SELECT t.id, t.NAME, t.sex, t.age, t.role_id, t.del_flag, t1.NAME AS roleName FROM USER t LEFT JOIN role t1 ON ( t1.id = t.role_id ) WHERE t.del_flag = 0 AND ( t.id = ? ) LIMIT ?
普通寫法(QueryWrapper)
public UserVO getUserVO(Long id) { UserVO userVO = this.baseMapper.selectJoinOne( UserVO.class, new MPJQueryWrapper<User>() .selectAll(User.class) .select("t1.name as role_name") .leftJoin("role t1 on (t.role_id = t1.id)") .eq("t.id", id)); return userVO; }
生成SQL:
SELECT t.id, t.NAME, t.sex, t.age, t.role_id, t.del_flag, t1.NAME AS role_name FROM USER t LEFT JOIN role t1 ON ( t.role_id = t1.id ) WHERE t.del_flag = 0 AND ( t.id = 1 )
運(yùn)行結(jié)果與之前完全相同,需要注意的是,這樣寫時(shí)在引用表名時(shí)不要使用數(shù)據(jù)庫(kù)中的原表名,主表默認(rèn)使用 t,其他表使用join語(yǔ)句中我們?yōu)樗鸬膭e名,如果使用原表名在運(yùn)行中會(huì)出現(xiàn)報(bào)錯(cuò)。
mybatis-plus-join 這款工具還是比較使用的,能更應(yīng)對(duì)項(xiàng)目中不是非常復(fù)雜的場(chǎng)景下的sql查詢,大大提高我們的生產(chǎn)效率,也希望后面的版本能夠帶給我們更多的驚喜
到此這篇關(guān)于SpringBoot中整合MyBatis-Plus-Join使用聯(lián)表查詢的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)MyBatis-Plus-Join 聯(lián)表查詢內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
jstl之map,list訪問(wèn)遍歷以及el表達(dá)式map取值的實(shí)現(xiàn)
下面小編就為大家?guī)?lái)一篇jstl之map,list訪問(wèn)遍歷以及el表達(dá)式map取值的實(shí)現(xiàn)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-03-03logback-spring.xml的內(nèi)容格式詳解
這篇文章主要介紹了logback-spring.xml的內(nèi)容格式詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的的朋友參考下吧2023-11-11Java程序中使用JavaMail發(fā)送帶圖片和附件的郵件
這篇文章主要介紹了Java程序中使用JavaMail發(fā)送帶圖片和附件的郵件,JavaMail是專門用來(lái)處理郵件的Java API,需要的朋友可以參考下2015-11-11MyBatis實(shí)現(xiàn)動(dòng)態(tài)查詢、模糊查詢功能
這篇文章主要介紹了MyBatis實(shí)現(xiàn)動(dòng)態(tài)查詢、模糊查詢功能,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-06-06在Java生產(chǎn)環(huán)境下進(jìn)行性能監(jiān)控與調(diào)優(yōu)的詳細(xì)過(guò)程
在Java生產(chǎn)環(huán)境下進(jìn)行性能監(jiān)控與調(diào)優(yōu)是一個(gè)復(fù)雜但重要的過(guò)程,它涉及到多個(gè)方面,包括代碼分析、JVM監(jiān)控、線程管理、垃圾收集優(yōu)化、內(nèi)存管理、數(shù)據(jù)庫(kù)交互等,下面我將提供一個(gè)詳細(xì)的概述和示例代碼,需要的朋友可以參考下2025-02-02詳解SpringBoot與SpringCloud的版本對(duì)應(yīng)詳細(xì)版
這篇文章主要介紹了詳解SpringBoot與SpringCloud的版本對(duì)應(yīng)詳細(xì)版,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09