1. 程式人生 > 其它 >Mybatis動態sql與分頁 Mybatis分頁查詢與動態SQL

Mybatis動態sql與分頁 Mybatis分頁查詢與動態SQL

Mybatis分頁查詢與動態SQL

 

一、Mybatis的分頁查詢

 

  (1)無條件的分頁的mapper檔案配置和Java程式碼實現

<!-- 傳入的引數型別為map,此時無需使用map.get("key")去獲得實際值,只需填入key值便可 -->
    <select id="findByPage" parameterType="map" resultMap="studentMap">
        select id,name,age,sex from student
        limit #{start},#{end}
    </select>
/*
     * 無條件分頁查詢
     */
    public List<Student> findByPage(int start,int end)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            Map<String,Object> param = new LinkedHashMap<String,Object>();
            param.put("start",start);
            param.put("end",end);
            
            List<Student> stuList;
            stuList = sqlSession.selectList(Student.class.getName()+".findByPage", param);
            
            System.out.println("新增查詢成功");
            
            return stuList;
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }

  (2)有條件的分頁的mapper檔案配置和Java程式碼實現

<select id="findByPageAndRequest" parameterType="map" resultMap="studentMap">
        select id,name,age,sex from student
        where name like #{name}
        limit #{start},#{end}
    </select>
/*
     * 有條件分頁查詢
     */
    public List<Student> findByPageAndRequest(String name,int start,int end)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            Map<String,Object> params = new LinkedHashMap<String,Object>();
            //當sql的條件有模糊匹配時,引數需前後帶上%
            params.put("name", "%"+name+"%");
            params.put("start", start);
            params.put("end", end);
            
            List<Student> stuList;
            stuList = sqlSession.selectList(Student.class.getName()
                    +".findByPageAndRequest", params);
            
            System.out.println("新增查詢成功");        
            return stuList;
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }

二、Mybatis的動態SQL

  Mybatis除了支援簡單的sql外,還支援多種動態sql語句,如條件判斷,引數遍歷,包含等等語法,下面通過一些例子簡單認識下Mybatis對動態sql的支援

  (1)動態條件查詢:查詢時編寫where條件,判斷傳入的引數不為空才予以拼接,條件寫在<if test="xx">標籤中

<select id="findAll" parameterType="map" resultMap="studentMap">
        select * from student
        <where>
            <if test="id!=null">
                and id = #{id}
            </if>
            <if test="name!=null">
                and name = #{name}
            </if>
            <if test="age!=null">
                and age = #{age}
            </if>
            <if test="sex!=null">
                and sex = #{sex}
            </if>
        </where>
    </select>
/*
     * 動態帶條件查詢
     */
    public List<Student> findAll(String id,String name,String age,String sex)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            Map<String,Object> stuMap = new HashMap<String,Object>();
            stuMap.put("id", id);
            stuMap.put("name", name);
            stuMap.put("age", age);
            stuMap.put("sex", sex);
            
            return sqlSession.selectList(Student.class.getName()+".findAll", stuMap);
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }

  (2)動態條件更新:查詢時編寫where條件,判斷傳入的引數不為空才予以拼接,其中判斷條件中xx=#{xx}後需要帶",",set標籤會自動判斷哪個是最後一個欄位,會自動去掉最後一個","號

<!-- set標籤會自動判斷哪個是最後一個欄位,會自動去掉最後一個","號 -->
    <update id="update" parameterType="map">
        update student
        <set>
            <if test="name!=null">
                name = #{name},
            </if>
            <if test="age!=null">
                age = #{age},
            </if>
            <if test="sex!=null">
                sex = #{sex},
            </if>
        </set>
        where id = #{id}
    </update>
/*
     * 動態帶條件更新
     */
    public List<Student> update(String id,String name,String age,String sex)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            Map<String,Object> updateMap = new HashMap<String,Object>();
            updateMap.put("id", id);
            updateMap.put("name", name);
            updateMap.put("age", age);
            updateMap.put("sex", sex);
            
            sqlSession.update(Student.class.getName()+".update",updateMap);
            
            sqlSession.commit();
            return null;
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }

  (3)動態條件刪除:遍歷傳入的引數,可以為陣列,也可以為list結構,判斷集合或陣列中的欄位值與表中某欄位值相匹配則刪除

<!-- 
        foreach用於遍歷陣列元素 
        open表示開始符號
        close表示結束符號
        separator表示中間分隔符
        item表示陣列引數,屬性值可以任意,但提倡與方法引數相同
    -->
    <delete id="dynamicDelete">
        delete from student where id in
        <foreach collection="array" open="(" close=")" separator="," item="ids">
            #{ids}
        </foreach>
    </delete>
    
    <delete id="dynamicDeleteList">
        delete from student where id in
        <foreach collection="list" open="(" close=")" separator="," item="ids">
            #{ids}
        </foreach>
    </delete>
/*
     * 動態帶條件刪除
     */
    public void dynamicDelete(String... ids)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            sqlSession.delete(Student.class.getName()+".dynamicDelete",ids);
            
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }
    
    /*
     * 動態帶條件List批量刪除
     */
    public void dynamicDeleteList(List<String> ids)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            sqlSession.delete(Student.class.getName()+".dynamicDeleteList",ids);
            
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }

  (4)動態條件增加:在編寫插入語句時,可通過<include refid="xx"/>標籤來引入不同的sql片段,而sql片段可事先定義並配置好,通過refid的值來關聯不同的片段從而實現對應欄位插入對應的值。

<!-- 可通過<include refid="xx"/>標籤來引入不同的sql片段,如<include refid="key"/>表示引數對應的表字段
     <include refid="value"/> 表示欄位對應的值-->
    <insert id="dynamicInsert" parameterType="dynamicstudent">
        insert into student(<include refid="key"/>) values(<include refid="value"/>)
    </insert>
    
    <!-- SQL片段對應欄位名 -->
    <sql id="key">
        <if test="id!=null">
            id,
        </if>
        <if test="name!=null">
            name,
        </if>
        <if test="age!=null">
            age,
        </if>
        <if test="sex!=null">
            sex
        </if>
    </sql>
    
    <!-- SQL片段對應占位符? -->
    <sql id="value">
        <if test="id!=null">
            #{id},
        </if>
        <if test="name!=null">
            #{name},
        </if>
        <if test="age!=null">
            #{age},
        </if>
        <if test="sex!=null">
            #{sex}
        </if>
    </sql>
/*
     * 動態插入資料
     */
    public void dynamicInsert(Student stu)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            sqlSession.insert(Student.class.getName()+".dynamicInsert", stu);
            
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }

 

一、Mybatis的分頁查詢

 

  (1)無條件的分頁的mapper檔案配置和Java程式碼實現

<!-- 傳入的引數型別為map,此時無需使用map.get("key")去獲得實際值,只需填入key值便可 -->
    <select id="findByPage" parameterType="map" resultMap="studentMap">
        select id,name,age,sex from student
        limit #{start},#{end}
    </select>
/*
     * 無條件分頁查詢
     */
    public List<Student> findByPage(int start,int end)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            Map<String,Object> param = new LinkedHashMap<String,Object>();
            param.put("start",start);
            param.put("end",end);
            
            List<Student> stuList;
            stuList = sqlSession.selectList(Student.class.getName()+".findByPage", param);
            
            System.out.println("新增查詢成功");
            
            return stuList;
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }

  (2)有條件的分頁的mapper檔案配置和Java程式碼實現

<select id="findByPageAndRequest" parameterType="map" resultMap="studentMap">
        select id,name,age,sex from student
        where name like #{name}
        limit #{start},#{end}
    </select>
/*
     * 有條件分頁查詢
     */
    public List<Student> findByPageAndRequest(String name,int start,int end)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            Map<String,Object> params = new LinkedHashMap<String,Object>();
            //當sql的條件有模糊匹配時,引數需前後帶上%
            params.put("name", "%"+name+"%");
            params.put("start", start);
            params.put("end", end);
            
            List<Student> stuList;
            stuList = sqlSession.selectList(Student.class.getName()
                    +".findByPageAndRequest", params);
            
            System.out.println("新增查詢成功");        
            return stuList;
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }

二、Mybatis的動態SQL

  Mybatis除了支援簡單的sql外,還支援多種動態sql語句,如條件判斷,引數遍歷,包含等等語法,下面通過一些例子簡單認識下Mybatis對動態sql的支援

  (1)動態條件查詢:查詢時編寫where條件,判斷傳入的引數不為空才予以拼接,條件寫在<if test="xx">標籤中

<select id="findAll" parameterType="map" resultMap="studentMap">
        select * from student
        <where>
            <if test="id!=null">
                and id = #{id}
            </if>
            <if test="name!=null">
                and name = #{name}
            </if>
            <if test="age!=null">
                and age = #{age}
            </if>
            <if test="sex!=null">
                and sex = #{sex}
            </if>
        </where>
    </select>
/*
     * 動態帶條件查詢
     */
    public List<Student> findAll(String id,String name,String age,String sex)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            Map<String,Object> stuMap = new HashMap<String,Object>();
            stuMap.put("id", id);
            stuMap.put("name", name);
            stuMap.put("age", age);
            stuMap.put("sex", sex);
            
            return sqlSession.selectList(Student.class.getName()+".findAll", stuMap);
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }

  (2)動態條件更新:查詢時編寫where條件,判斷傳入的引數不為空才予以拼接,其中判斷條件中xx=#{xx}後需要帶",",set標籤會自動判斷哪個是最後一個欄位,會自動去掉最後一個","號

<!-- set標籤會自動判斷哪個是最後一個欄位,會自動去掉最後一個","號 -->
    <update id="update" parameterType="map">
        update student
        <set>
            <if test="name!=null">
                name = #{name},
            </if>
            <if test="age!=null">
                age = #{age},
            </if>
            <if test="sex!=null">
                sex = #{sex},
            </if>
        </set>
        where id = #{id}
    </update>
/*
     * 動態帶條件更新
     */
    public List<Student> update(String id,String name,String age,String sex)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            Map<String,Object> updateMap = new HashMap<String,Object>();
            updateMap.put("id", id);
            updateMap.put("name", name);
            updateMap.put("age", age);
            updateMap.put("sex", sex);
            
            sqlSession.update(Student.class.getName()+".update",updateMap);
            
            sqlSession.commit();
            return null;
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }

  (3)動態條件刪除:遍歷傳入的引數,可以為陣列,也可以為list結構,判斷集合或陣列中的欄位值與表中某欄位值相匹配則刪除

<!-- 
        foreach用於遍歷陣列元素 
        open表示開始符號
        close表示結束符號
        separator表示中間分隔符
        item表示陣列引數,屬性值可以任意,但提倡與方法引數相同
    -->
    <delete id="dynamicDelete">
        delete from student where id in
        <foreach collection="array" open="(" close=")" separator="," item="ids">
            #{ids}
        </foreach>
    </delete>
    
    <delete id="dynamicDeleteList">
        delete from student where id in
        <foreach collection="list" open="(" close=")" separator="," item="ids">
            #{ids}
        </foreach>
    </delete>
/*
     * 動態帶條件刪除
     */
    public void dynamicDelete(String... ids)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            sqlSession.delete(Student.class.getName()+".dynamicDelete",ids);
            
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }
    
    /*
     * 動態帶條件List批量刪除
     */
    public void dynamicDeleteList(List<String> ids)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            sqlSession.delete(Student.class.getName()+".dynamicDeleteList",ids);
            
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }

  (4)動態條件增加:在編寫插入語句時,可通過<include refid="xx"/>標籤來引入不同的sql片段,而sql片段可事先定義並配置好,通過refid的值來關聯不同的片段從而實現對應欄位插入對應的值。

<!-- 可通過<include refid="xx"/>標籤來引入不同的sql片段,如<include refid="key"/>表示引數對應的表字段
     <include refid="value"/> 表示欄位對應的值-->
    <insert id="dynamicInsert" parameterType="dynamicstudent">
        insert into student(<include refid="key"/>) values(<include refid="value"/>)
    </insert>
    
    <!-- SQL片段對應欄位名 -->
    <sql id="key">
        <if test="id!=null">
            id,
        </if>
        <if test="name!=null">
            name,
        </if>
        <if test="age!=null">
            age,
        </if>
        <if test="sex!=null">
            sex
        </if>
    </sql>
    
    <!-- SQL片段對應占位符? -->
    <sql id="value">
        <if test="id!=null">
            #{id},
        </if>
        <if test="name!=null">
            #{name},
        </if>
        <if test="age!=null">
            #{age},
        </if>
        <if test="sex!=null">
            #{sex}
        </if>
    </sql>
/*
     * 動態插入資料
     */
    public void dynamicInsert(Student stu)
    {
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtil.getSqlSession();
            
            sqlSession.insert(Student.class.getName()+".dynamicInsert", stu);
            
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession();
        }
    }