07. mybatis 動(dòng)態(tài) sql

07. mybatis 動(dòng)態(tài) sql

MyBatis 的一個(gè)強(qiáng)大的特性之一通常是它的動(dòng)態(tài) SQL 能力。 如果你有使用JDBC 或其他 相似框架的經(jīng)驗(yàn),你就明白條件地串聯(lián) SQL 字符串在一起是多么的痛苦,確保不能忘了空 格或在列表的最后省略逗號(hào)。動(dòng)態(tài) SQL 可以徹底處理這種痛苦。

常用的動(dòng)態(tài)sql標(biāo)簽

  • if
  • where
  • trim
  • set
  • choose(when,otherwise)
  • foreach

1、if元素

if標(biāo)簽可以對(duì)傳入的條件進(jìn)行判斷

如下案例:判斷是否傳入id,若傳入則id查詢,若不傳入則全部查詢。

    <select id="findByTerm" parameterType="map" resultMap="userResult">
        select 
            id,user_name,password,reg_time 
        from 
            t_user 
        <if test="id!=null &amp;&amp; id!='' &amp;&amp; id !=0">
            where id=#{id}
        </if>

    </select>

測試:

    public void testFindByTerm() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", "4");
        List<UserPo> userPos = userDao.findByTerm(map);
        logger.debug(userPos.toString());
    }

2、where元素

對(duì)于查詢條件個(gè)數(shù)不確定的情況,可使用<where>元素。

    <select id="findByTerm" parameterType="map" resultMap="userResult">
        select 
            id,user_name,password,reg_time 
        from 
            t_user 
        <where >
            <if test="id!=null &amp;&amp; id!='' &amp;&amp; id !=0">
                id=#{id}
            </if>
            <if test="userName!=null &amp;&amp; userName!='' ">
                and user_name=#{userName}
            </if>
        </where>
    </select>

<where>元素會(huì)進(jìn)行判斷,如果它包含的標(biāo)簽中有返回值的話,它就插入一個(gè)‘where’。此外,如果標(biāo)簽返回的內(nèi)容是以AND 或OR 開頭,它會(huì)剔除掉AND或OR。

測試:

    public void testFindByTerm() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", "4");
        map.put("userName", "張三");
        List<UserPo> userPos = userDao.findByTerm(map);
        logger.debug(userPos.toString());
    }

3、trim元素

where標(biāo)簽,其實(shí)用trim 也可以表示,當(dāng)WHERE后緊隨AND或則OR的時(shí)候,就去除AND或者OR。prefix前綴,prefixOverrides覆蓋首部指定內(nèi)容

    <select id="findByTerm" parameterType="map" resultMap="userResult">
        select 
            id,user_name,password,reg_time 
        from 
            t_user 
        <trim prefix="where" prefixOverrides="and|or" >
            <if test="id!=null &amp;&amp; id!='' &amp;&amp; id !=0">
                id=#{id}
            </if>
            <if test="userName!=null &amp;&amp; userName!='' ">
                and user_name=#{userName}
            </if>
        </trim>
    </select>

測試:

    public void testFindByTerm() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", "4");
        map.put("userName", "張三");
        List<UserPo> userPos = userDao.findByTerm(map);
        logger.debug(userPos.toString());
    }

4、set元素

set標(biāo)簽,可以在需要更新的語句中,通過添加判斷條件更新需要的指定列。

同時(shí)也可以把最后的一個(gè)逗號(hào)去掉。

    <update id="updatePortion" parameterType="UserPo" >
        update t_user 
            <set>
                <if test="userName != null &amp;&amp; userName != ''">user_name = #{userName},</if>
                <if test="password != null &amp;&amp; password != ''">password = #{password},</if>
                <if test="regTime != null &amp;&amp; regTime != ''">reg_time = #{regTime}</if>
            </set>
            where id = #{id}
    </update>

5、foreach元素

foreach標(biāo)簽,可以循環(huán)遍歷指定的數(shù)組或者集合。

如下案例:批量刪除

    <delete id="batchDelete">
        delete from t_user
            where id in
            <foreach collection="array" item="id" open="(" separator="," close=")">
                #{id}
            </foreach>
    </delete>

測試:

    public void testBatchDelete() {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtil.getSqlSession();
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            String id="4,6,";
            String[] idList = id.split(","); 
            
            userDao.batchDelete(idList);
            sqlSession.close();
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            sqlSession.close();
        }
    }

6、XML中的特殊字符

如果 mybatis 使用 XML 配置,不可避免會(huì)遇到對(duì)一些XML來說的特殊字符。

字符 對(duì)應(yīng)的XML 含義
< &lt; 小于
> &rt; 大于
& &amp;
' &apos; 單引號(hào)
" &quot; 雙引號(hào)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容