yulichang / mybatis-plus-join

支持连表查询的mybatis-plus,mybatis-plus风格的连表操作提供wrapper.leftJoin(),wrapper.rightJoin()等操作
https://yulichang.github.io/mybatis-plus-join-doc/
Apache License 2.0
971 stars 113 forks source link
mybatis mybatis-plus mysql orm sql toolkit

Mybatis-Plus-Join-Logo

MyBatis-Plus-Join

为简化开发工作、提高生产率而生

maven code style

MyBatis-Plus 多表查询的扩展 | 演示工程 | 使用文档 | 点个Star支持一下吧 (☆▽☆)

QQ群:680016987 或者 添加作者微信,备注MPJ,加入微信群
添加作者微信,备注MPJ,加入微信群

使用文档WIKI

使用方法

安装

使用

Lambda形式用法(MPJLambdaWrapper)

简单的连表查询

class test {
    @Resource
    private UserMapper userMapper;

    void testJoin() {
        //和Mybatis plus一致,MPJLambdaWrapper的泛型必须是主表的泛型,并且要用主表的Mapper来调用
        MPJLambdaWrapper<UserDO> wrapper = JoinWrappers.lambda(UserDO.class)
                .selectAll(UserDO.class)//查询user表全部字段
                .select(UserAddressDO::getTel)//查询user_address tel 字段
                .selectAs(UserAddressDO::getAddress, UserDTO::getUserAddress)//别名
                .select(AreaDO::getProvince, AreaDO::getCity)
                .leftJoin(UserAddressDO.class, UserAddressDO::getUserId, UserDO::getId)
                .leftJoin(AreaDO.class, AreaDO::getId, UserAddressDO::getAreaId)
                .eq(UserDO::getId, 1)
                .like(UserAddressDO::getTel, "1")
                .gt(UserDO::getId, 5);

        //连表查询 返回自定义ResultType
        List<UserDTO> list = userMapper.selectJoinList(UserDTO.class, wrapper);

        //分页查询 (需要启用 mybatis plus 分页插件)
        Page<UserDTO> listPage = userMapper.selectJoinPage(new Page<>(2, 10), UserDTO.class, wrapper);
    }
}

对应sql

SELECT  
    t.id, t.name, t.sex, t.head_img, 
    t1.tel, t1.address AS userAddress,
    t2.province, t2.city 
FROM 
    user t 
    LEFT JOIN user_address t1 ON t1.user_id = t.id 
    LEFT JOIN area t2 ON t2.id = t1.area_id 
WHERE (
    t.id = ? 
    AND t1.tel LIKE ? 
    AND t.id > ?)

说明:

一对多查询

class test {
    @Resource
    private UserMapper userMapper;

    @Test
    void testResultMap() {
        MPJLambdaWrapper<UserDO> wrapper = new MPJLambdaWrapper<>(User.class)
                .selectAll(UserDO.class)
                //对多查询
                .selectCollection(AddressDO.class, UesrDTO::getAddressList)
                //对一查询
                .selectAssociation(AddressDO.class, UesrDTO::getAddress)
                .leftJoin(AddressDO.class, AddressDO::getUserId, UserDO::getId);

        List<UserDTO> dtoList = userMapper.selectJoinList(UserDTO.class, wrapper);

        //关于对多分页查询
        //由于嵌套结果方式会导致结果集被折叠,因此分页查询的结果在折叠后总数会减少,所以无法保证分页结果数量正确。
    }
}

MPJLambdaWrapper其他功能

使用文档 wiki