MyBatis動態sql

什麼是動態sql

  MyBatis的強大特性之一便是動態sql,之前我們在用JDBC的時候,根據不同條件拼接SQL語句是很痛苦的事情,利用MyBatis的動態sql特性便可以解決這個問題。

動態sql的組成元素

  在學習動態sql之前,先來了解下ONGL,什麼是ONGL呢?它和EL表達式差不多,是一種功能強大的表達式語言,用來獲取和設置Java對象的屬性。動態sql的實際使用元素並不多,無非就那幾種,但是它們帶來了靈活性的同時,很大程度上提高了程序的可讀性和可維護性。下面看下組成元素:
1)if元素:簡單的條件判斷
2)choose(when、otherwise)元素:相當於java中的switch
3)trim、where、set元素:重點,見代碼詳解


  1. sql映射文件

<!--
        查詢時如果某些條件沒有加上可能會出現sql拼裝錯誤的問題
        解決方法:
            1. 給where後面加上1=1,以後的條件都and xxx.
            2. mybatis使用where標籤來將所有的查詢條件包括在內,mybatis就會將where標籤中多餘的and或or去除掉
                ps:where只會去除掉第一個多出來的or或and 
            3. 後面多出的and或者or,where標籤不能解決,用trim標籤解決(自定義字符串截取的規則)
                <trim prefix="where" prefixOverrides="" suffix="" suffixOverrides="and"></trim> 
                    prefix="": 前綴,
                    prefixOverrides="":去掉前面的某些字符串,
                    suffix="":後綴,
                    suffixOverrides="":去掉後面的某些字符串
     -->
    <select id="getEmpsByConditionIf" resultType="com.zgz.MyBatis.bean.Employee">
        select id, last_name lastName, email, gender from tbl_employee
        <where>
            <!-- 
                OGNL表達式:
                    1. test裏面寫判斷的條件
                    2. 特殊符號要轉義
                    3. ognl表達式會進行字符串和數字的轉換判斷,如:"1"==1 
            -->
            <if test="id!=null">
                id = #{id}
            </if>
            <if test="lastName!=null and lastName!=''">
                and last_name like #{lastName}
            </if>
            <if test="email!=null and email.trim()!=&quot;&quot;">
                and email = #{email}
            </if>
            <if test="gender==0 or gender==1">
                and gender = #{gender}
            </if>
        </where>
    </select>

    <!--
        where標籤用在查詢的時候,寫在sql語句外面
        set標籤用在更新的時候,寫在sql語句外面  
    -->
    <update id="updateEmp">
        update tbl_employee
        <set>
            <if test="lastName!=null">
                last_name=#{lastName},
            </if>
            <if test="email!=null">
                email=#{email},
            </if>
            <if test="gender!=null">
                gender=#{gender}
            </if>
        </set>
        <where>
            <if test="id!=null">
                id=#{id}
            </if>
        </where>
    </update>

  2.測試的接口方法

//攜帶了那個字段查詢條件就帶上這個字段的值
    public List<Employee> getEmpsByConditionIf(Employee employee);

    //更新操作
    public void updateEmp(Employee employee);

  3. 測試類

@Test
    public void testDynamicSQL() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapperDynamicSQL mapperDynamicSQL = openSession.getMapper(EmployeeMapperDynamicSQL.class);
            Employee employee = new Employee(3, "xiaoli", null, null);

            //測試where標籤
//          List<Employee> emps = mapperDynamicSQL.getEmpsByConditionIf(employee);
//          for(Employee emp: emps) {
//              System.out.println(emp);
//          }

            //測試set標籤
//          mapperDynamicSQL.updateEmp(employee);
//          openSession.commit();   //手動提交數據
        } finally {
            openSession.close();
        }
    }

4)foreach元素:重點,見代碼詳解


  1. sql映射文件

<select id="getEmpsByConditionForeach" resultType="com.zgz.MyBatis.bean.Employee">
        select * from tbl_employee where id in
        <!--
            foreach標籤:
                collection:指定要遍歷的集合,可以是List,數組,Set等集合
                item:示集合中每一個元素進行迭代時的別名
                separator:各個元素的分隔符 
                open和close:配置以什麼符號將這些集合中的元素包裝起來
                index:當前元素在集合中的位置下標
         -->
        <foreach collection="ids" item="item" separator=","
            open="(" close=")">
            #{item}
        </foreach>
    </select>

  2.測試的接口方法

//測試foreach
    public List<Employee> getEmpsByConditionForeach(@Param("ids")List<Integer> ids);

  3. 測試類

@Test
    public void testDynamicSQL() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        try {
            EmployeeMapperDynamicSQL mapperDynamicSQL = openSession.getMapper(EmployeeMapperDynamicSQL.class);
            Employee employee = new Employee(3, "xiaoli", null, null);

            //測試foreach標籤
            List<Integer> ids = new ArrayList<>();
            ids.add(1);
            ids.add(2);
            ids.add(3);
            ids.add(4);
            List<Employee> emps = mapperDynamicSQL.getEmpsByConditionForeach(ids);
            for(Employee emp :  emps) {
                System.out.println(emp);
            }

        } finally {
            openSession.close();
        }
    }

 以上代碼均未給出mybatis的主配置文件,自行添加

5)test元素:判斷真假

總結

  要抓住重點:常用的無非就是if,where,set,foreach一定要掌握。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章