概要
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);
}
2462

被折叠的 条评论
为什么被折叠?



