Mybatis-Plus 实现多表联合查询+分页+查询条件

Mybatis plus 自己只能完成单表操作,所以如果想要实现多表,需要借助 Mybatis 实现:首先引入mybatis-plus依赖,这里就不演示了

返回结果集封装,传递分页以及查询的参数,主要代码在 Service 中

@RequestMapping("getClazz")
    public ResultJson<UserRole> getClazz(Integer page, Integer limit, String name) {
        return ResultJson.success(
       	 	PageWeb.build(demoService.getClazz(page, limit, name))
        );
  
    }

Service 层代码:搭建的框架没什么好说的,直接看方法:

@Service
public class DemoServiceImpl extends ServiceImpl<DemoMapper, Role> implements DemoService {
    @Resource
    private DemoMapper demoMapper;
// 返回结果集是 IPage 类型的,泛型是想要传递的实体
    @Override
    public IPage<UserRole> getClazz(Integer page, Integer limit, String name) {
    	// 创建 IPage 的实体类,传递 page limit 实现分页
        IPage<UserRole> page1 = new Page<>(page, limit);
        // 调用 Mapper 层方法,把 IPage 的实现类和查询条件传递
        return demoMapper.getClazz(page1, name);
    }
}

Mapper 层方法:

public interface DemoMapper extends BaseMapper<Role> {
	// 返回结果同上是 IPage 对象
    IPage<UserRole> getClazz(IPage<UserRole> page, @Param("name") String name);
}

xml sql 语句

<?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.xxxx.qcby.mapper.DemoMapper">
	<--! 返回结果集合,id 是唯一标识,type 是结果类型-->
    <resultMap id="UserWithRole" type="com.xxxx.qcby.entity.User">
        <id column="id" jdbcType="BIGINT" property="id"/>
        <result column="user_name" jdbcType="VARCHAR" property="userName"/>
        <result column="password" jdbcType="VARCHAR" property="password"/>
        <result column="sex" jdbcType="INTEGER" property="sex"/>
        <--! 实现连表查询 property 是实体对象,id 是传递的参数,select 是查询语句 -->
        <collection property="userRole" column="id" select="listRole"/>
    </resultMap>

    <select id="getClazz" resultMap="UserWithRole">
        select * from t_user
        <where>
            <if test="name != null">
                user_name like concat('%', #{name}, '%')
            </if>
        </where>
    </select>

    <select id="listRole" resultType="String">
        select role_name
        from t_role r left join ref_user_role rur on r.id = rur.role_id
        where rur.user_id = #{userId}
    </select>
</mapper>

在这里插入图片描述
已实现,总结:其实就是使用 Mybatis-Plus 的分页加上 Mybatis 的基础,熟悉使用 Mybatis 即可

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_努力努力再努力_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值