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查詢分頁內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- springboot使用mybatis一對多的關聯查詢問題記錄
- 解讀Mapper與Mapper.xml文件之間匹配的問題
- Mybatis中resultMap的Colum和property屬性詳解
- MyBatis動態SQL如何實現前端指定返回字段
- MyBatis延遲加載策略深入探究