MyBatis如何配置動態SQL語句

MyBatis配置動態SQL語句

在 MyBatis 的 SQL映射文件中,有時候需要根據一些查詢條件,來選擇不同的SQL語句,如果每一個場景都重寫SQL,很顯然效率沒有很高,而 MyBatis 的動態SQL很好的解決了這種問題,根據條件動態的處理 SQL, 特別簡單的說就是,寫一次SQL,但是根據分支等的跳轉,在多個場景下也可以使用,例如:

  • 當查詢條件由於參數不同而無法確定具體是什麼,可以使用 <where> 標籤包含
  • <where> 可以使用 <if test="...."> 分條件進行處理,實現動態
  • <foreach> 遍歷標籤放到後面代碼中具體說

在此之外,動態SQL同時結局了,在原生 JDBC 中需要拼接SQL語句時由於書寫問題,而導致報錯

(一) where 和 if 標籤

UserMapper 接口

/**
* 根據條件查詢
* @return
*/
List<User> findUserByCondition(User user);

UserMapper.xml

<select id="findUserByCondition" resultType="cn.ideal.domain.User" parameterType="cn.ideal.domain.User">
	select  * from user
    <where>
   		<if test="username != null">
        	and username = #{username}
        </if>
        <if test="gender != null">
            and gender = #{gender}
        </if>
    </where>
</select>

注意:在SQL中,“and” 用來拼接已有一個或多個查詢條件的語句,當此語句爲第一個查詢條件的時候,會因爲 <where> 的存在屏蔽第一個 “and”

MyBatisTest

/**
 * 根據條件查詢
 * @throws Exception
 */
@Test
public void testFindByCondition() throws Exception{
    User user = new User();
    user.setUsername("湯姆");
    user.setGender("女");

    List<User> users = userMapper.findUserByCondition(user);
    for (User u : users){
        System.out.println(u);
    }

執行效果

(二) 複用SQL

有一些語句,在我們的程序中,使用的頻率特別高,這個時候,我們也可以對其進行,單獨的配置,然後達到複用的效果

首先,我們需要對其進行簡單的聲明

<sql id="xxxxx">
	<!-- 複用的SQL -->
</sql>

在需要引用的地方,我們可以這樣引用

<where>
	include refid="xxxxx"></include>
	<!-- 可能還用引用別的 -->
</where>

(三) foreach標籤

提出這樣一種需求,在用戶中查詢尋多個id,例如(12,16,17)我們可以這樣寫SQL

select * from user where id=12 or id=16 or id=17

或者這樣

select * from user where id in (12,16,17)

而這種情況下,我們需要向SQL中傳遞一個數據或者List類型的參數,然後使用 <foreach> 標籤去遍歷然後解析

UserMapper 接口

/**
     * 根據QueryUserVo中提供的id集合,查詢用戶信息
     * @param vo
     * @return
     */
    List<User> findUserInIds(QueryUserVo vo);

UserMapper.xml

<select id="findUserInIds" resultType="cn.ideal.domain.UserInstance" parameterType="cn.ideal.domain.QueryUserVo">
	select * from user
	<where>
        <if test="ids != null and ids.size() > 0">
        	<foreach collection="ids" open="and id in (" close=")" item="uid" separator=",">
            	#{uid}
            </foreach>
        </if>
    </where>
</select>

解釋一下

  • collection 指定輸入對象中的集合屬性
  • item 爲每次遍歷生成的對象名
  • open爲開始遍歷時拼接的字符串
  • close爲結束便利時要拼接的字符串
  • separator爲遍歷兩個對象中間需要拼接的串

本例中,我哦們使用了 select * from user where id in (12,16,17) 這種形式,如果想使用 or那種形式,只需要修改拼接格式就可以了

/**
 * 根據QueryUserVo中提供的id集合,查詢用戶信息
 * @throws Exception
 */
    @Test
    public void testfindUserInIds() throws Exception{
        QueryUserVo vo = new QueryUserVo();
        List<Integer> list = new ArrayList<Integer>();
        list.add(12);
        list.add(16);
        list.add(17);
        vo.setIds(list);

        List<User> users = userMapper.findUserInIds(vo);
        for (User u : users){
            System.out.println(u);
        }
    }

執行效果

結尾

如果文章中有什麼不足,歡迎大家留言交流,感謝朋友們的支持!

如果能幫到你的話,那就來關注我吧!如果您更喜歡微信文章的閱讀方式,可以關注我的公衆號

在這裏的我們素不相識,卻都在爲了自己的夢而努力 ❤

一個堅持推送原創開發技術文章的公衆號:理想二旬不止

發佈了75 篇原創文章 · 獲贊 58 · 訪問量 3175
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章