好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Mybatis实现联表查询并且分页功能

今天同学突然问我这个怎么搞。
然后自己搞了一下发现这个玩意有坑。。就记录一下

0. 表结构

person表

cat表

一个person有多个cat

实体类就这么写

1. 实体类

Person实体类

@Data public class Person implements Serializable { private static final long serialVersionUID = - 70682701290685641L ; private Integer personid ; private String firstname ; private String lastname ; private List < Cat > cats ; }

Cat实体类

@Data public class Cat implements Serializable { private static final long serialVersionUID = - 39783356260765568L ; private Integer id ; private String name ; /** * 猫的历史 */ private String history ; /** * 猫的特征 */ private String features ; /** * 大概的样子 */ private String imgurl ; private Integer personId ; }

2. Mapper配置文件

PersonDao.xml

<? 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.liliya.dao.PersonDao" > <!-- 返回的Person映射Map --> <resultMap type = "com.liliya.entity.Person" id = "PersonMap" > <result property = "personid" column = "PersonId" jdbcType = "INTEGER" /> <result property = "firstname" column = "FirstName" jdbcType = "VARCHAR" /> <result property = "lastname" column = "LastName" jdbcType = "VARCHAR" /> <collection property = "cats" ofType = "Cat" > <result property = "id" column = "id" jdbcType = "INTEGER" /> <result property = "name" column = "name" jdbcType = "VARCHAR" /> <result property = "history" column = "history" jdbcType = "VARCHAR" /> <result property = "features" column = "features" jdbcType = "VARCHAR" /> <result property = "imgurl" column = "imgUrl" jdbcType = "VARCHAR" /> <result property = "personId" column = "person_id" jdbcType = "INTEGER" /> </collection> </resultMap>   <!--查询单个--> <select id = "queryById" resultMap = "PersonMap" > select personid, firstname, lastname, id, name, history, features, imgurl, person_id from mybatis.person p inner join mybatis.cat c on p.PersonId = c.person_id and PersonId= #{PersonId} </select>   </mapper>

上面这个是查询单个人的,但是分页没有这么简单
一开始我以为是这么写的,就简单的加一个limit

<select id = "queryById" resultMap = "PersonMap" > select personid, firstname, lastname, id, name, history, features, imgurl, person_id from mybatis.person p inner join mybatis.cat c on p.PersonId = c.person_id limit #{page},#{step} </select>

然后查出来就是这个吊样。。。很明显嘛,不对我的胃口。。

后面我准备放弃的时候突然想到可以来一个子查询。。。

然后我就写出了这样的sql
,在子查询里面套子查询。。。实现limit分页的效果

select personid , firstname , lastname , id , name , history , features , imgurl , person_id from mybatis . person p left join mybatis . cat c on p . PersonId = c . person_id where PersonId in ( select pp . PersonId from ( select person . PersonId from person limit 2 , 2 ) as pp );

然后sql放到上面就搞好了
跑出来的效果就非常nice

到此这篇关于Mybatis联表查询并且分页的文章就介绍到这了,更多相关Mybatis查询分页内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/zhihu_0/article/details/115142044

查看更多关于Mybatis实现联表查询并且分页功能的详细内容...

  阅读:21次