1. 程式人生 > >MyBatis動態SQL,分頁查詢,List/Array/Map查詢.

MyBatis動態SQL,分頁查詢,List/Array/Map查詢.


  • 動態sql
xml中程式碼
<select id="SelectTrends" parameterType="com.***.***.entity.Doctor"
            resultMap="BaseResultMap">
        select
        *
        from doctor
        <where>
            <if test="id != null">
                AND id = #{id,jdbcType=VARCHAR}
            </if>
            <if test="name != null">
                AND name = #{name,jdbcType=CHAR}
            </if>
        </where>
</select>

id為對映類中方法名稱,where內條件根據需求增減.查詢結果最好使用List接收,避免查詢結果為多條時報錯.

  •  分頁查詢

方法有很多,可以看https://blog.csdn.net/chenbaige/article/details/70846902的步驟,已經寫的很詳細.我與他的方法不同:

首先實體類繼承一個基類.

​實體類中建立基類BaseEntity
public BaseEntity() {
        HttpServletRequest request = ((ServletRequestAttributes) 
                           RequestContextHolder.currentRequestAttributes()).getRequest();
        String pageSizeStr = request.getParameter("pageSize");
        String pageNoStr = request.getParameter("pageNo");

        if (StringUtils.isNotBlank(pageSizeStr)) {
            int size = Integer.parseInt(pageSizeStr);
            this.pageSize = size > 0 ? size : PAGE_SIZE;

        } else {
            this.pageSize = PAGE_SIZE;
        }

        if (StringUtils.isNotBlank(pageNoStr)) {
            int number = Integer.parseInt(pageNoStr);
            this.pageNo = number > 0 ? number - 1 : PAGE_NO;
        } else {
            this.pageNo = PAGE_NO;
        }

        this.beginNo = pageNo * pageSize;
    }

}

需要分頁查詢的使其實體類繼承BaseEntity,實體類就會含有pageNo(頁碼),pageSize(每頁條數),beginNo(查詢起始條數)屬性.

           controller層傳入的引數需要含有pageNo,pageSize屬性.

xml中程式碼

<select id="selectLimit"  parameterType="com.***.***.entity.Doctor" 
    resultMap="BaseResultMap">
    select *
    from doctor
        <where>
            **************
        </where>
        limit #{beginNo},#{pageSize}
</select>

需要注意的是 limit #{beginNo},#{pageSize}中的值名稱要與基類中屬性名一致.

  • List/Array/Map查詢
​xml中程式碼

<select id="selectList" parameterType="com.***.***.Entity.Doctor" 
    resultMap="BaseResultMap">
    select * from doctor
    <where>
        id in
            <foreach collection="Ids" item="id" index="index" open="(" close=")" 
                     separator=",">
                #{id}
            </foreach>
    </where>
</select>

實體類中含有屬性Ids屬性(資料庫中很可能無此欄位,可以建立新實體類DoctorNew繼承Doctor實體類,這樣 parameterType="com.***.***.***.DoctorNew").
需要注意的是,當傳遞的List(或Array,Map)為空時,SQL語句報錯,所以傳遞前最好判斷容器內容.

foreach元素的屬性主要有(item,index,collection,open,separator,close).
item表示集合中每一個元素進行迭代時的別名
index指定一個名字,用於表示在迭代過程中,每次迭代到的位置
open表示該語句以什麼開始
separator表示在每次進行迭代之間以什麼符號作為分隔符
close表示以什麼結束
collection表示傳入引數屬性.該屬性是必須指定的, 在不同情況下,該屬性的值是不一樣的,主要有一下3種情況: 
    1.如果傳入的引數是單引數且引數型別是一個List的時候,collection屬性值為list .
    2.如果傳入的引數是單引數且引數型別是一個Array陣列的時候,collection的屬性值為array .
    3.如果傳入的引數是多個的時候,可以封裝成一個Map,當然單引數也可以封裝成map,實際上如果你在傳入引數的時候,在MyBatis裡面也是會把它封裝成一個Map的,map的key就是引數名,所以這個時候collection屬性值就是傳入的List或array物件在自己封裝的map裡面的key.
​

​