java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Mybatis-Plus-Join表连接插件集成

Mybatis-Plus-Join表连接插件集成过程

作者:刘火锅

Mybatis-Plus-Join是Mybatis-Plus的扩展插件,支持左、右、内连接查询,保持原有开发风格,通过JoinLambdaWrapper配置连接关系与查询条件,简化多表关联操作,提升复杂SQL编写效率

概要

Mybatis-Plus-Join 是基于 Mybatis-Plus 的扩展插件,提供了简便的表连接查询功能,支持左连接、右连接和内连接等操作,同时保持 Mybatis-Plus 的使用风格。

官方文档:https://mpj.aicats.cc/

安装配置

1.添加依赖

在 pom.xml 中添加以下依赖:

<dependency>
    <groupId>com.github.yulichang</groupId>
    <artifactId>mybatis-plus-join-boot-starter</artifactId>
    <version>1.4.5</version>
</dependency>

2.配置继承结构

Mapper 层继承

import icu.mhb.mybatisplus.plugln.base.mapper.JoinBaseMapper;

public interface UserMapper extends JoinBaseMapper<User> {
   
}

Service 接口继承

import icu.mhb.mybatisplus.plugln.base.service.JoinIService;

public interface UserService extends JoinIService<User> {
   
}

Service 实现层继承

import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends JoinServiceImpl<UserMapper, User> implements UserService {
   
}

基本使用方法

1. 创建 JoinLambdaWrapper

在 Service 中可直接使用 joinLambdaWrapper() 方法:

// 方式一:通过 Service 直接获取
JoinLambdaWrapper<User> wrapper = userService.joinLambdaWrapper();

// 方式二:手动创建
JoinLambdaWrapper<User> wrapper = new JoinLambdaWrapper<>(User.class);

2. 添加表连接

支持三种连接方式:

// 左连接
wrapper.leftJoin(Department.class, Department::getId, User::getDeptId);

// 右连接
wrapper.rightJoin(Department.class, Department::getId, User::getDeptId);

// 内连接
wrapper.innerJoin(Department.class, Department::getId, User::getDeptId);

3. 添加查询条件

wrapper.eq(Department::getName, "技术部")
       .like(User::getName, "张")
       .gt(User::getAge, 25);

4. 结束连接并执行查询

// 结束当前连接(重要!)
wrapper.end();

// 执行查询
List<UserVO> result = userService.joinList(wrapper, UserVO.class);

多表连接示例

public List<UserVO> findUsersWithMultiJoin() {
    JoinLambdaWrapper<User> wrapper = userService.joinLambdaWrapper();
    
    // 第一重连接:部门表
    wrapper.leftJoin(Department.class, Department::getId, User::getDeptId)
           .selectAs(Department::getName, UserVO::getDeptName)
           .end();
    
    // 第二重连接:职位表
    wrapper.leftJoin(Position.class, Position::getUserId, User::getId)
           .eq(Position::getLevel, "P7")
           .selectAs(Position::getName, UserVO::getPositionName)
           .end();
    
    return userService.joinList(wrapper, UserVO.class);
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文