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 即可