您好,登錄后才能下訂單哦!
這篇文章主要介紹了SpringBoot中怎么整合MyBatisPlus Join使用聯表查詢的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇SpringBoot中怎么整合MyBatisPlus Join使用聯表查詢文章都會有所收獲,下面我們一起來看看吧。
相信大家在日常的開發中用的最多的就是 mybatis-plus了吧,作為一個 MyBatis (opens new window)的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。
聯表查詢一直是 mybatis-plus 的短板之處,當需要聯表查詢時,還得打開 xml 文件寫入長長的 sql 語句。于是有需求就有產出,mybatis-plus-join 出世了,可以以類似 mybatis-plus 中 QueryWrapper 的方式來進行聯表查詢,下面一起來體驗吧!
<!-- 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>
配置文件信息
spring: # 數據源配置 datasource: # 連接池類型 type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.cj.jdbc.Driver # 數據庫名稱 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 # 實體類路徑 type-aliases-package: com.asurplus.entity configuration: # 駝峰轉換 map-underscore-to-camel-case: true # 是否開啟緩存 cache-enabled: false # 打印sql,正式環境關閉 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 全局配置 global-config: db-config: #主鍵類型 0:"數據庫ID自增",1:"該類型為未設置主鍵類型", 2:"用戶輸入ID",3:"全局唯一ID (數字類型唯一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; } }
建庫
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、插入數據
INSERT INTO `role` VALUES (1, '超級管理員', 0); INSERT INTO `user` VALUES (1, 'Asurplus', 1, 18, 1, 0);
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對象", 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 = "刪除狀態(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> * 服務實現類 * </p> * * @author lizhou * @since 2022-12-14 */ @Service public class UserServiceImpl extends MPJBaseServiceImpl<UserMapper, User> implements UserService { }
注意:這里我們繼承了 MPJBaseServiceImpl
vo類
import com.asurplus.entity.User; import lombok.Data; @Data public class UserVO extends User { private String roleName; }
聯表查詢
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 = ? )
聯表分頁查詢
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 )
運行結果與之前完全相同,需要注意的是,這樣寫時在引用表名時不要使用數據庫中的原表名,主表默認使用 t,其他表使用join語句中我們為它起的別名,如果使用原表名在運行中會出現報錯。
關于“SpringBoot中怎么整合MyBatisPlus Join使用聯表查詢”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“SpringBoot中怎么整合MyBatisPlus Join使用聯表查詢”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。