1. 程式人生 > >Spring+SpringMVC+MyBatis深入學習及搭建(五)——動態sql

Spring+SpringMVC+MyBatis深入學習及搭建(五)——動態sql

mybatis核心:對sql語句進行靈活操作,通過表示式進行判斷,對sql進行靈活拼接、組裝。

mybatis提供各種標籤方法實現動態拼接sql。

1. if&where

1.2 需求

使用者資訊綜合查詢列表和使用者資訊查詢列表總數這兩個statement的定義使用動態sql。

對查詢條件進行判斷,如果輸入引數不為空才進行查詢條件拼接。

1.3 mapper.xml

    <select id="findUserList" parameterType="joanna.yan.mybatis.entity.UserQueryVo" resultType="joanna.yan.mybatis.entity.UserCustom"
> SELECT * FROM USER <!--where可以自動去掉條件中的第一個and --> <where> <if test="userCustom!=null"> <if test="userCustom.sex!=null and userCustom.sex!=''"> and user.sex=#{userCustom.sex} </if>
<if test="userCustom.username!=null and userCustom.username!=''"> and user.username LIKE '%${userCustom.username}%' </if> </if> </where> </select>

<select id="findUserCount" parameterType="joanna.yan.mybatis.entity.UserQueryVo"
resultType="int"> SELECT count(*) FROM USER <!--where可以自動去掉條件中的第一個and --> <where> <if test="userCustom!=null"> <if test="userCustom.sex!=null and userCustom.sex!=''"> and user.sex=#{userCustom.sex} </if> <if test="userCustom.username!=null and userCustom.username!=''"> and user.username LIKE '%${userCustom.username}%' </if> </if> </where> </select>

1.4測試程式碼

    @Test
    public void findUserListTest() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        //建立包裝物件,設定查詢條件
        UserQueryVo userQueryVo=new UserQueryVo();
        UserCustom userCustom=new UserCustom();
        //由於這裡使用動態sql,如果不設定某個值,條件不會拼接在sql中
//        userCustom.setSex("1");
        userCustom.setUsername("張三丰");
        userQueryVo.setUserCustom(userCustom);
        List<UserCustom> list=userMapper.findUserList(userQueryVo);
        System.out.println(list);
    }

列印的sql:如果不設定sex的值,條件不會拼接在sql中

2.sql片段

2.1 需求

將上邊實現的動態sql判斷程式碼塊抽取出來,組成一個sql片段。其它的statement中就可以引用sql片段。方便程式設計師進行開發。

2.2 定義sql片段

    <!--定義sql片段
        id:sql片段的唯一標識
        
        經驗:1.是基於單表來定義sql片段的,這樣的話這個sql片段可重用性才高
            2.在sql片段中不要包括where
      -->
    <sql id="query_user_where">
        <if test="userCustom!=null">
            <if test="userCustom.sex!=null and userCustom.sex!=''">
                and user.sex=#{userCustom.sex}
            </if>
            <if test="userCustom.username!=null and userCustom.username!=''">
                and user.username LIKE '%${userCustom.username}%'
            </if>
        </if>
    </sql>

2.3 引用sql片段

在mapper.xml中定義statement中引用sql片段:

    <select id="findUserList" parameterType="joanna.yan.mybatis.entity.UserQueryVo" resultType="joanna.yan.mybatis.entity.UserCustom">
        SELECT * FROM USER
        <!--where可以自動去掉條件中的第一個and  -->
        <where>
            <!--引用sql片段的id,如果refid指定的id不在本mapper檔案中,需要在前邊加namespace  -->
            <include refid="query_user_where"></include>
            <!--在這裡還可以引用其它的sql片段  -->
        </where>
    </select>

<select id="findUserCount" parameterType="joanna.yan.mybatis.entity.UserQueryVo" resultType="int"> SELECT count(*) FROM USER <!--where可以自動去掉條件中的第一個and --> <where> <!--引用sql片段的id,如果refid指定的id不在本mapper檔案中,需要在前邊加namespace --> <include refid="query_user_where"></include> <!--在這裡還可以引用其它的sql片段 --> </where> </select>

3. foreach

向sql傳遞陣列或List,mybatis使用foreach解析。

3.1 需求

在使用者查詢列表和查詢總數的statement中增加多個id輸入查詢。

sql語句如下,兩種方法:

SELECT * FROM USER WHERE id=1 OR id=10 OR id=16

SELECT * FROM USER WHERE id IN(1,10,16)

3.2 在輸入引數型別中新增List<Integer> ids傳入多個id

3.3 修改mapper.xml

WHERE id=1 OR id=10 OR id=16

在前面的查詢條件中,查詢條件定義成了一個sql片段,現在我們需要修改sql片段。

    <!--定義sql片段
        id:sql片段的唯一標識
        
        經驗:1.是基於單表來定義sql片段的,這樣的話這個sql片段可重用性才高
            2.在sql片段中不要包括where
      -->
    <sql id="query_user_where">
        <if test="userCustom!=null">
            <if test="userCustom.sex!=null and userCustom.sex!=''">
                and user.sex=#{userCustom.sex}
            </if>
            <if test="userCustom.username!=null and userCustom.username!=''">
                and user.username LIKE '%${userCustom.username}%'
            </if>
            <if test="ids!=null">
                <!--使用foreach遍歷傳入的ids
                    collection:指定輸入物件中集合屬性
                    item:每個遍歷生成的物件名
                    open:開始遍歷時拼接的串
                    close:結束遍歷時拼接的串
                    separator:遍歷的兩個物件中需要拼接的串
                 -->
                 <!--是要實現下邊的sql拼接:
                     AND (id=1 OR id=10 OR id=16)
                   -->
                <foreach collection="ids" item="user_id" open="AND (" close=")" separator="or">
                    <!--每個遍歷需要拼接的串  -->
                    id=#{user_id}
                </foreach>
            </if>
        </if>
    </sql>

3.4 測試程式碼

    @Test
    public void findUserListTest() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        //建立包裝物件,設定查詢條件
        UserQueryVo userQueryVo=new UserQueryVo();
        UserCustom userCustom=new UserCustom();
        //由於這裡使用動態sql,如果不設定某個值,條件不會拼接在sql中
//        userCustom.setSex("1");
        userCustom.setUsername("小明");
        //傳入多個id
        List<Integer> ids=new ArrayList<>();
        ids.add(1);
        ids.add(10);
        ids.add(16);
        userQueryVo.setIds(ids);
        userQueryVo.setUserCustom(userCustom);
        List<UserCustom> list=userMapper.findUserList(userQueryVo);
        System.out.println(list);
    }

 如果此文對您有幫助,微信打賞我一下吧~ 

相關推薦

Spring+SpringMVC+MyBatis深入學習搭建()——動態sql

mybatis核心:對sql語句進行靈活操作,通過表示式進行判斷,對sql進行靈活拼接、組裝。 mybatis提供各種標籤方法實現動態拼接sql。 1. if&where 1.2 需求 使用者資訊綜合查詢列表和使用者資訊查詢列表總數這兩個statement的定義使用動態sql。 對查詢條件進行判斷

Spring+SpringMVC+MyBatis深入學習搭建(三)——MyBatis全局配置文件解析

保持 nbsp 延遲加載 行為 span 方便 doc ima actor 轉載請註明出處:http://www.cnblogs.com/Joanna-Yan/p/6874672.html 前面有寫到Spring+SpringMVC+MyBatis深入學習及搭建(二)&

Spring+SpringMVC+MyBatis深入學習搭建(四)——MyBatis輸入映射與輸出映射

指定 2.6 face 生成 shm hashmap ace and 包裝 轉載請註明出處:http://www.cnblogs.com/Joanna-Yan/p/6878529.html 前面有講到Spring+SpringMVC+MyBatis深入學習及搭建(三)&

Spring+SpringMVC+MyBatis深入學習搭建(八)——MyBatis查詢緩存

idt rtu void spring 寫到 查詢緩存 修改 針對 target 轉載請註明出處:http://www.cnblogs.com/Joanna-Yan/p/6956206.html 前面講到:Spring+SpringMVC+MyBatis深入學習及搭建(

Spring+SpringMVC+MyBatis深入學習搭建(十)——MyBatis逆向工程

cat springmvc blank 不為 tex llc root from ssi 轉載請註明出處:http://www.cnblogs.com/Joanna-Yan/p/6973266.html 前面講到:Spring+SpringMVC+MyBatis深入學習及

Spring+SpringMVC+MyBatis深入學習搭建(十一)——SpringMVC架構

框架 ppi spring框架 edit 不同的 com get request html 轉載請註明出處:http://www.cnblogs.com/Joanna-Yan/p/6985816.html 前面講到:Spring+SpringMVC+MyBatis深入學習

Spring+SpringMVC+MyBatis深入學習搭建(十四)——SpringMVCMyBatis整合

文件拷貝 conf lips glib ide doc from ive body 轉載請註明出處:http://www.cnblogs.com/Joanna-Yan/p/7010363.html 前面講到:Spring+SpringMVC+MyBatis深入學習及搭建(

Spring+SpringMVC+MyBatis深入學習搭建(二)——MyBatis原始Dao開發和mapper代理開發

oid 方法註入 內部 需要 com 配置文件信息 lec lang auth 前面有寫到Spring+SpringMVC+MyBatis深入學習及搭建(一)——MyBatis的基礎知識。MybatisFirst中存在大量重復的代碼。這次簡化下代碼: 使用MyBatis開發

Spring+SpringMVC+MyBatis深入學習搭建(四)——MyBatis輸入映射與輸出映射(轉發同上)

resultmap 根據 except 就會 ash 用戶名 mvc html like 原地址:http://www.cnblogs.com/shanheyongmu/p/7121556.html 1. 輸入映射 通過parameterType指定輸入參數的類型,類型可

Spring+SpringMVC+MyBatis深入學習搭建(九)——MyBatisSpring整合

1.整合思路需要Spring通過單例方式管理SqlSessionFactory。Spring和MyBatis整合生成代理物件,使用SqlSessionFactory建立SqlSession。(Spring和MyBatis整合自動完成)持久層的mapper都需要由Spring進

Spring+SpringMVC+MyBatis深入學習搭建(八)——MyBatis查詢快取

1.什麼是查詢快取 mybatis提供查詢快取,用於減輕資料庫壓力,提高資料庫效能。 mybatis提供一級快取和二級快取。 一級快取是SqlSession級別的快取。在操作資料庫時需要構造sqlSession物件,在物件中有一個數據結構(HashMap)用於儲存快取資料。不同的sqlSession之間

Spring+SpringMVC+MyBatis深入學習搭建(七)——MyBatis延遲載入

1.什麼是延遲載入 resultMap可以實現高階對映(使用association、collection實現一對一及一對多對映),association、collection具備延遲載入功能。 需求: 如果查詢訂單並且關聯查詢使用者資訊。如果先查詢訂單資訊即可滿足要求,當我們需要查詢使用者資訊時再查下使用

Spring+SpringMVC+MyBatis深入學習搭建(六)——MyBatis關聯查詢

1.商品訂單資料模型 1.1資料模型分析思路 (1)每張表記錄的資料內容   分模組對每張表記錄的內容進行熟悉,相當於你學習系統需求(功能)的過程。 (2)每張表重要的欄位設定   非空欄位、外來鍵欄位 (3)資料庫級別表與表之間的關係   外來鍵關係 (4)表與表之間的業務關係   在分析表與表之間的

Spring+SpringMVC+MyBatis深入學習搭建(四)——MyBatis輸入對映與輸出對映

1. 輸入對映 通過parameterType指定輸入引數的型別,型別可以是簡單型別、hashmap、pojo的包裝型別。 1.1 #{}與${} #{}實現的是向prepareStatement中的預處理語句設定引數值,sql語句中#{}表示一個佔位符即? <select id="findUse

Spring+SpringMVC+MyBatis深入學習搭建(三)——MyBatis全域性配置檔案解析

MyBatis的全域性配置檔案SqlMapConfig.xml,配置內容和順序如下: properties(屬性) setting(全域性配置引數) typeAliases(類名別名) typeHandlers(類名處理器) objectFactory(物件工廠) plugins(外掛) environm

Spring+SpringMVC+MyBatis深入學習搭建】17.SpringMVC攔截器

1.攔截器定義 Spring Web MVC的處理器攔截器類似於Servlet開發中的過濾器Filter,用於對處理器進行預處理和後處理。 定義攔截器,實現HandlerInterceptor介面。介面中提供三個方法。 package joanna.yan.ssm.interceptor; imp

Spring,SpringMVC,Mybatis (SSM)框架的搭建

搭建SSM框架參照一下步驟:1.提供ssm所需jar包 這些jar包包括三個框架所需要的,就不一一列舉所屬了 aopalliance-1.0.jar asm-3.3.1.jar aspectjweaver.jar c3p0-0.9.1.jar cglib-2.2.2.j

SSM(Spring+SpringMVC+Mybatis)框架超詳細搭建指南(利用Maven構建專案)

其實這是我實習生涯開始後的第一個任務,但是當時太忙了一直沒有時間記錄,就按照教程走了。剛好現在實習結束了有些時間,把整個搭建的過程還有一些坑記錄下來還是很有必要的。 DEMO https://github.com/mgsky1/aboutSpring/tree/ma

SSM(Spring+SpringMVC+Mybatis)框架搭建詳細教程【附源代碼Demo】

oid rep images end 訪問靜態文件 into *** 寫到 where http://www.cnblogs.com/qixiaoyizhan/p/7751732.html 【前言】   應某網絡友人邀約,需要一個SSM框架的Demo作為基礎學習資料,於

使用idea搭建Maven+SSM(Spring+SpringMVC+Mybatis)框架(一、使用Maven創建新工程)

post eight 9.png 圖片 tis 本地包 end pen nbsp 一、新建Maven項目 1、如圖創建簡單java web application。 2、如圖填寫組織唯一標識和項目唯一標識 3、如圖照做 4、點擊finish即可完成項目創建,如圖為創建