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

概要

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);
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值