網(wǎng)頁設(shè)計(jì)圖片超鏈接海曙seo關(guān)鍵詞優(yōu)化方案
背景
使用pageHelper時(shí),發(fā)現(xiàn)分頁數(shù)據(jù)異常,經(jīng)過排查發(fā)現(xiàn)是resultMap 的問題。
resultMap介紹
在使用mybatis時(shí),我們經(jīng)常會(huì)使用在xml文件中編寫一些復(fù)雜的sql語句,例如多表的join,在映射實(shí)體類時(shí),又會(huì)使用到resultMap,將查詢的數(shù)據(jù)庫字段與實(shí)體類字段進(jìn)行映射對(duì)照。
resultMap 元素是 MyBatis 中最重要最強(qiáng)大的元素。它可以讓你從 90% 的 JDBC ResultSets 數(shù)據(jù)提取代碼中解放出來,并在一些情形下允許你進(jìn)行一些 JDBC 不支持的操作。實(shí)際上,在為一些比如連接的復(fù)雜語句編寫映射代碼的時(shí)候,一份 resultMap 能夠代替實(shí)現(xiàn)同等功能的數(shù)千行代碼。ResultMap 的設(shè)計(jì)思想是,對(duì)簡(jiǎn)單的語句做到零配置,對(duì)于復(fù)雜一點(diǎn)的語句,只需要描述語句之間的關(guān)系就行了。
舉例
當(dāng)我們編寫了一個(gè)非常復(fù)雜的resultMap時(shí),例如如下。
<!-- 非常復(fù)雜的結(jié)果映射 -->
<resultMap id="detailedBlogResultMap" type="Blog"><constructor><idArg column="blog_id" javaType="int"/></constructor><result property="title" column="blog_title"/><association property="author" javaType="Author"><id property="id" column="author_id"/><result property="username" column="author_username"/><result property="password" column="author_password"/><result property="email" column="author_email"/><result property="bio" column="author_bio"/><result property="favouriteSection" column="author_favourite_section"/></association><collection property="posts" ofType="Post"><id property="id" column="post_id"/><result property="subject" column="post_subject"/><association property="author" javaType="Author"/><collection property="comments" ofType="Comment"><id property="id" column="comment_id"/></collection><collection property="tags" ofType="Tag" ><id property="id" column="tag_id"/></collection><discriminator javaType="int" column="draft"><case value="1" resultType="DraftPost"/></discriminator></collection>
</resultMap>
請(qǐng)把你的目光聚集到collection標(biāo)簽上,對(duì)應(yīng)Java 實(shí)體類屬性為List posts;
有兩張表 blog 和 post, 一對(duì)多的關(guān)系。
一個(gè)blog 博客,可以用多篇post文章。
我們查詢博客以及文章,并且裝配到統(tǒng)一個(gè)實(shí)體類中。
select blog.*,post.title,post.status from blog left join post using(post_id);
假設(shè)查詢到5條數(shù)據(jù),兩個(gè)博客,分別對(duì)應(yīng)的1、4篇文章。那么被resultMap映射過會(huì)得到一個(gè)擁有兩個(gè)元素的集合,文章數(shù)據(jù)被封裝到對(duì)應(yīng)的集合屬性中。
但是如果我們?cè)趕ql最后加入 limi 2, 這樣查到的分頁數(shù)據(jù)就是不準(zhǔn)確的了。
查出來還是兩個(gè)元素的集合,但是第二個(gè)元素的posts 屬性卻只有一篇文章,和我們預(yù)期嚴(yán)重不符合
會(huì)出現(xiàn)各種情況,posts屬性數(shù)據(jù)不完整,或者是其他數(shù)據(jù)不正確的情況。
結(jié)論
所以當(dāng)我們需要使用resultMap + collection來進(jìn)行復(fù)雜映射時(shí),慎重使用 limit 關(guān)鍵字,以及一些插件(pageHelper)