mybatis學習筆記(5) ---- 動態Sql

mybatis學習筆記(5) ---- 動態Sql

mybatis中的一大特性就是動態sql,在傳統的JDBC編程中,根據條件編寫,拼接SQL語句很容易出錯,因此mybatis引入了動態sql。動態Sql元素和JSTL(jSP標準標籤庫)很像。動態sql的本質就是對sql進行靈活拼接和組裝。

if標籤

if標籤最常用到,在查詢和刪除更新數據的時候作判斷時結合test屬性使用。主要用來判斷參數是否合法,如參數不能爲null等。

mapper.xml
<select id="find" parameterType="com.excellent.po.User" resultType="com.excellent.po.User">
        select * from user
        <where>
            <if test="user != null">
                <if test="user.id != null">
                    AND id &gt; #{user.id}
                </if>
                <if test="user.sex != null">
                    AND sex = #{user.sex}
                </if>
            </if>
        </where>
    </select>
test
 @Test
    public void test6(){
        SqlSession sqlSession = factory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setId(10);
        user.setSex("1");
        List<User> list = mapper.find(user);
        for(User user1 : list){
            System.out.println(user1);
        }
        sqlSession.close();

    }

foreach標籤

顧名思義,這個標籤是用來循環遍歷的,可以實現多個相同樣式條件的查詢。

mapper.xml

<select id="findById" parameterType="java.util.ArrayList" resultType="java.util.Map">

        <!--
            select * from user where id in (1,10,16,22)
            collection:指定輸入 對象中集合屬性
            item:每個遍歷生成對象中
            open:開始遍歷時拼接的串
            close:結束遍歷時拼接的串
            separator:遍歷的兩個對象中需要拼接的串
        -->

        SELECT *
        FROM user
        WHERE id in
        <foreach item="i"  collection="list" open="("
                 separator="," close=")">
            #{i}
        </foreach>

    </select>

set標籤

  • mapper.xml
<mapper namespace="com.excellent.mapper.UserMapper">
    <insert id="adduser" parameterType="com.excellent.po.User">
        update user
        <set>
            <if test="user.sex != null">
                 sex = #{user.sex}
            </if>
            <if test="user.username != null">
                and username = #{user.username}
            </if>
        </set>
                where id = #{user.id}
    </insert>

Sql片段

將一些常用的,出現機率高的sql語句抽出來,用sql標籤封裝起來,就像一個函數一樣,用的時候,只需要調用即可,無需重寫。減少代碼冗餘。

  • mapper.xml
 <sql id="mysql1">
        select * from user
    </sql>

 <select id="findAll" resultType="com.excellent.po.User">
        <include refid="mysql1"/>
  </select>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章