mybatis常用條件查詢總結(jié)(迭代一)

目錄

1.mybatis中大于等于小于等于的寫法

2.mybatis動(dòng)態(tài)查詢條件組裝

3.mybatis批量條件

4.mybatis時(shí)間查詢實(shí)現(xiàn)分頁(yè)總結(jié)

1.mybatis中大于等于小于等于的寫法

第一種寫法(1):

原符號(hào)       <        <=      >       >=       &        '        "
替換符號(hào)    <    <=   >    >=   &   '  "
例如:sql如下:
create_date_time >= #{startTime} and  create_date_time <= #{endTime}

第二種寫法(2):

大于等于
<![CDATA[ >= ]]>
小于等于
<![CDATA[ <= ]]>
例如:sql如下:
create_date_time <![CDATA[ >= ]]> #{startTime} and  create_date_time <![CDATA[ <= ]]> #{endTime}

2.mybatis動(dòng)態(tài)查詢條件組裝如下:

 <!--  if(判斷參數(shù)) - 將實(shí)體類不為空的屬性作為where條件 -->  
    <select id="getStudentList_if" resultMap="resultMap_studentEntity" parameterType="liming.student.manager.data.model.StudentEntity">  
        SELECT ST.STUDENT_ID,  
               ST.STUDENT_NAME,  
               ST.STUDENT_SEX,  
               ST.STUDENT_BIRTHDAY,  
               ST.STUDENT_PHOTO,  
               ST.CLASS_ID,  
               ST.PLACE_ID  
          FROM STUDENT_TBL ST   
         WHERE  
        <if test="studentName !=null ">  
            ST.STUDENT_NAME LIKE CONCAT(CONCAT('%', #{studentName, jdbcType=VARCHAR}),'%')  
        </if>  
        <if test="studentSex != null and studentSex != '' ">  
            AND ST.STUDENT_SEX = #{studentSex, jdbcType=INTEGER}  
        </if>  
        <if test="studentBirthday != null ">  
            AND ST.STUDENT_BIRTHDAY = #{studentBirthday, jdbcType=DATE}  
        </if>  
        <if test="classId != null and classId!= '' ">  
            AND ST.CLASS_ID = #{classId, jdbcType=VARCHAR}  
        </if>  
        <if test="classEntity != null and classEntity.classId !=null and classEntity.classId !=' ' ">  
            AND ST.CLASS_ID = #{classEntity.classId, jdbcType=VARCHAR}  
        </if>  
        <if test="placeId != null and placeId != '' ">  
            AND ST.PLACE_ID = #{placeId, jdbcType=VARCHAR}  
        </if>  
        <if test="placeEntity != null and placeEntity.placeId != null and placeEntity.placeId != '' ">  
            AND ST.PLACE_ID = #{placeEntity.placeId, jdbcType=VARCHAR}  
        </if>  
        <if test="studentId != null and studentId != '' ">  
            AND ST.STUDENT_ID = #{studentId, jdbcType=VARCHAR}  
        </if>   
    </select> 

3.mybatis批量條件

在Mybatis的xml配置中使用集合,主要是用到了foreach動(dòng)態(tài)語(yǔ)句。foreach元素的屬性主要有 item,index,collection,open,separator,close。item表示集合中每一個(gè)元素進(jìn)行迭代時(shí)的別名,index指定一個(gè)名字,用于表示在迭代過(guò)程中,每次迭代到的位置,open表示該語(yǔ)句以什么開(kāi)始,separator表示在每次進(jìn)行迭代之間以什么符號(hào)作為分隔符,close表示以什么結(jié)束。
說(shuō)明:以下示例關(guān)于MySQL數(shù)據(jù)庫(kù)。由于**傳入的參數(shù)是多個(gè)**,因此把它們封裝成一個(gè)Map了,當(dāng)然單參數(shù)也可以用Map。.xml文件的部分代碼如下:
<update id="updateMessage" parameterType="java.util.Map"> update cx_customer_message set MODIFYTIME = SYSDATE() where MEMBERID = #{memberId, jdbcType=VARCHAR}  and MESSAGE_CLASSIFY = #{messageClassify, jdbcType=VARCHAR}  and MESSAGE_CODE in <foreach collection="messageCode" item="item" index="index" open="(" separator="," close=")"> #{item,jdbcType=VARCHAR}  </foreach></update>


MessageMapper.Java
public interface MessageMapper{ //更新 public int updateMessage(Map<String, Object> message);}

MessageManager.java
public interface MessageManager { public int updateMessage(MessageReq messageReq); }

MessageManagerImpl.java
@Componentpublic class MessageManagerImpl implements MessageManager { @Autowired private MessageMapper messageMapper; @Override public int updateMessage(MessageReq messageReq) { int affectRows; Map<String, Object> message= new HashMap<String, Object>(); message.put("memberId", messageReq.getMemberId()); message.put("messageClassify",messageReq.getMessageClassify()); message.put("messageCode", messageReq.getMessageCode()); affectRows = messageMapper.updateDefualtMessage(message); return affectRows; } }

![](http://static.blog.csdn.net/images/save_snippets.png)

collection屬性是必須指定的,在不同情況下該屬性的值是不一樣的:
如上述例子,傳入的參數(shù)是多個(gè)時(shí),collection屬性值為傳入List或array在**map里面的key**;傳入的是單參數(shù)且參數(shù)類型是List時(shí),collection屬性值為list;傳入的是單參數(shù)且參數(shù)類型array時(shí),collection的屬性值為array。

3.1mybatis批量插入

1. 在接口UserMapper中添加批量增加方法。

**[java]** [view plain](http://blog.csdn.net/mahoking/article/details/46811865#) [copy](http://blog.csdn.net/mahoking/article/details/46811865#)
 [print](http://blog.csdn.net/mahoking/article/details/46811865#)[?](http://blog.csdn.net/mahoking/article/details/46811865#)

/** 
    * 批量增加操作 
    * @param users 
    */  
   public void batchInsertUsers(List<User> users);  

2.在User.xml中添加批量增加操作的配置。
**[html]** [view plain](http://blog.csdn.net/mahoking/article/details/46811865#) [copy](http://blog.csdn.net/mahoking/article/details/46811865#)
 [print](http://blog.csdn.net/mahoking/article/details/46811865#)[?](http://blog.csdn.net/mahoking/article/details/46811865#)

<!-- 批量增加操作 -->  
    <insert id="batchInsertUsers" parameterType="java.util.List">  
        insert into mhc_user(userName,password) values  
        <foreach collection="list" item="item" index="index" separator=",">  
            (#{item.userName},#{item.password})  
        </foreach>  
    </insert>  

       由于批量增加的方法中參數(shù)為L(zhǎng)ist,所以parameterType的值為[Java](http://lib.csdn.net/base/java).util.List。
3. 創(chuàng)建批量操作的工具類BatchDataUtils,編寫批量增加方法。
**[java]** [view plain](http://blog.csdn.net/mahoking/article/details/46811865#) [copy](http://blog.csdn.net/mahoking/article/details/46811865#)
 [print](http://blog.csdn.net/mahoking/article/details/46811865#)[?](http://blog.csdn.net/mahoking/article/details/46811865#)

/** 
     * 批量增加操作 
     * @param users 
     */  
    public static void batchInsertUsers(List<User> users){  
          
        SqlSessionFactory ssf = MyBatisUtil.getSqlSessionFactory();  
        SqlSession session = ssf.openSession();  
          
        try {  
            UserMapper userMapper = session.getMapper(UserMapper.class);  
            userMapper.batchInsertUsers(users);  
            session.commit();  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            MyBatisUtil.closeSession(session);  
        }  
    }  

3.2批量刪除條件

**批量刪除操作步驟**
1. 在接口UserMapper中添加刪除增加方法。
**[java]** [view plain](http://blog.csdn.net/mahoking/article/details/46811865#) [copy](http://blog.csdn.net/mahoking/article/details/46811865#)
 [print](http://blog.csdn.net/mahoking/article/details/46811865#)[?](http://blog.csdn.net/mahoking/article/details/46811865#)

/** 
     * 批量刪除操作 
     * @param ids 
     */  
    public void batchDeleteUsers(List ids);  

2.在User.xml中添加批量增加操作的配置。
**[html]** [view plain](http://blog.csdn.net/mahoking/article/details/46811865#) [copy](http://blog.csdn.net/mahoking/article/details/46811865#)
 [print](http://blog.csdn.net/mahoking/article/details/46811865#)[?](http://blog.csdn.net/mahoking/article/details/46811865#)

<!-- 批量刪除操作 -->  
    <delete id="batchDeleteUsers" parameterType="java.util.List">  
        delete from mhc_user where id in  
        <foreach collection="list" index="index" item="item" open="(" close=")" separator=",">  
            #{item}  
        </foreach>  
    </delete>  

由于批量刪除的方法中參數(shù)為L(zhǎng)ist,所以parameterType的值為java.util.List。
3. 在批量操作的工具類BatchDataUtils中編寫批量刪除方法。
**[java]** [view plain](http://blog.csdn.net/mahoking/article/details/46811865#) [copy](http://blog.csdn.net/mahoking/article/details/46811865#)
 [print](http://blog.csdn.net/mahoking/article/details/46811865#)[?](http://blog.csdn.net/mahoking/article/details/46811865#)

/** 
     * 批量刪除操作 
     * @param ids 
     */  
    public static void batchDeleteUsers(List ids){  
        SqlSessionFactory ssf = MyBatisUtil.getSqlSessionFactory();  
        SqlSession session = ssf.openSession();  
          
        try {  
            UserMapper userMapper = session.getMapper(UserMapper.class);  
            userMapper.batchDeleteUsers(ids);  
            session.commit();  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            MyBatisUtil.closeSession(session);  
        }  
} 

3.3批量查詢操作步驟

1. 在接口UserMapper中添加批量查詢方法。
**[java]** [view plain](http://blog.csdn.net/mahoking/article/details/46811865#) [copy](http://blog.csdn.net/mahoking/article/details/46811865#)
 [print](http://blog.csdn.net/mahoking/article/details/46811865#)[?](http://blog.csdn.net/mahoking/article/details/46811865#)

/** 
    * 批量查詢操作  
    * @param ids 
    * @return 
    */  
    public List<User> batchSelectUsers(List ids);  

2.在User.xml中添加批量查詢操作的配置。
**[html]** [view plain](http://blog.csdn.net/mahoking/article/details/46811865#) [copy](http://blog.csdn.net/mahoking/article/details/46811865#)
 [print](http://blog.csdn.net/mahoking/article/details/46811865#)[?](http://blog.csdn.net/mahoking/article/details/46811865#)

<!-- 批量查詢操作 -->  
    <select id="batchSelectUsers" resultType="User">  
        select *  
        from mhc_user where id in  
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">  
        #{item}  
        </foreach>  
    </select>  

由于批量查詢的方法的返回為L(zhǎng)ist<User>,所以resultType的值為User,即com.mahaochen.mybatis.domain.User。詳見(jiàn)configuration.xml中。
**[html]** [view plain](http://blog.csdn.net/mahoking/article/details/46811865#) [copy](http://blog.csdn.net/mahoking/article/details/46811865#)
 [print](http://blog.csdn.net/mahoking/article/details/46811865#)[?](http://blog.csdn.net/mahoking/article/details/46811865#)

<typeAliases>  
        <!-- 注冊(cè)實(shí)體Bean -->  
        <typeAlias type="com.mahaochen.mybatis.domain.User" alias="User"/>  
</typeAliases>  

3. 創(chuàng)建批量操作的工具類BatchDataUtils,編寫批量查詢方法。

**[java]** [view plain](http://blog.csdn.net/mahoking/article/details/46811865#) [copy](http://blog.csdn.net/mahoking/article/details/46811865#)
 [print](http://blog.csdn.net/mahoking/article/details/46811865#)[?](http://blog.csdn.net/mahoking/article/details/46811865#)

/** 
    * 批量查詢操作  
    * @param ids 
    * @return 
    */  
    public static List<User> batchSelectUsers(List ids){  
        SqlSessionFactory ssf = MyBatisUtil.getSqlSessionFactory();  
        SqlSession session = ssf.openSession();  
        List<User> users = null;  
        try {  
            UserMapper userMapper = session.getMapper(UserMapper.class);  
            users = userMapper.batchSelectUsers(ids);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            MyBatisUtil.closeSession(session);  
        }  
        return users;  
    }  
}  

3.4批量更細(xì)操作步驟

1. 在接口UserMapper中添加批量增加方法。
**[java]** [view plain](http://blog.csdn.net/mahoking/article/details/46811865#) [copy](http://blog.csdn.net/mahoking/article/details/46811865#)
 [print](http://blog.csdn.net/mahoking/article/details/46811865#)[?](http://blog.csdn.net/mahoking/article/details/46811865#)

/** 
     * 批量更新操作  
     * @param ids 
     */  
    public void batchUpdateUsers(List users);  

2.在User.xml中添加批量更新操作的配置。
**[html]** [view plain](http://blog.csdn.net/mahoking/article/details/46811865#) [copy](http://blog.csdn.net/mahoking/article/details/46811865#)
 [print](http://blog.csdn.net/mahoking/article/details/46811865#)[?](http://blog.csdn.net/mahoking/article/details/46811865#)

<!-- 批量更新操作 -->  
    <!-- FOR MySQL mysql需要數(shù)據(jù)庫(kù)連接配置&allowMultiQueries=true   
        例如:jdbc:mysql://127.0.0.1:3306/mhc?allowMultiQueries=true -->  
    <update id="batchUpdateUsers" parameterType="java.util.List">  
        <foreach collection="list" item="item" index="index" open="" close="" separator=";">  
        update mhc_user   
        <set>  
            userName = #{item.userName}, password = #{item.password}  
        </set>  
        where id = #{item.id}  
        </foreach>  
    </update>  
      
    <!-- 【擴(kuò)展知識(shí)】 FOR Oracle  有以下三種方式-->  
    <!-- 方式一 -->  
    <update id="batchUpdateUsers01" parameterType="java.util.List">  
        <foreach collection="list" item="item" index="index" open="begin" close=";end;" separator=";" >   
            update mhc_user   
            <set>         
                userName = #{item.userName}, password = #{item.password}  
            </set>  
            where id = #{item.id}  
        </foreach>  
    </update>  
    <!-- 方式二 -->  
    <update id="batchUpdateUsers02" parameterType="java.util.List">  
        <foreach collection="list" item="item" index="index" open="begin" close="end;" separator="" >   
            update mhc_user   
            <set>         
                userName = #{item.userName}, password = #{item.password}  
            </set>  
            where id = #{item.id};  
        </foreach>  
    </update>  
    <!-- 方式三 -->  
    <update id="batchUpdateUsers03" parameterType="java.util.List">  
        begin  
        <foreach collection="list" item="item" index="index" separator="" >   
            update mhc_user   
            <set>         
                userName = #{item.userName}, password = #{item.password}  
            </set>  
            where id = #{item.id};  
        </foreach>  
        end;  
    </update>  

         由于批量更新的方法中參數(shù)為L(zhǎng)ist,所以parameterType的值為java.util.List。

3. 創(chuàng)建批量操作的工具類BatchDataUtils,編寫批量更新方法。
**[java]** [view plain](http://blog.csdn.net/mahoking/article/details/46811865#) [copy](http://blog.csdn.net/mahoking/article/details/46811865#)
 [print](http://blog.csdn.net/mahoking/article/details/46811865#)[?](http://blog.csdn.net/mahoking/article/details/46811865#)

/** 
    * 批量更新操作  
    * @param users 
    */  
   public static void batchUpdateUsers(List users){  
    SqlSessionFactory ssf = MyBatisUtil.getSqlSessionFactory();  
    SqlSession session = ssf.openSession();  
      
    try {  
        UserMapper userMapper = session.getMapper(UserMapper.class);  
        userMapper.batchUpdateUsers(users);  
        session.commit();  
    } catch (Exception e) {  
        e.printStackTrace();  
    } finally {  
        MyBatisUtil.closeSession(session);  
    }  
   } 

4mybatis分頁(yè)查詢實(shí)現(xiàn)總結(jié)

4.1分頁(yè)實(shí)現(xiàn)根據(jù)時(shí)間的范圍
<!-- param_where_query 查詢條件 -->
    <sql id="param_where_query">
        <trim prefix="(" suffix=")" prefixOverrides="and">
            <!-- 自增主鍵 -->
            <if test="id != null">
                and id in
                <foreach item="item" index="index" collection="id" open="("
                    separator="," close=")">#{item}</foreach>
            </if>
            <!-- memberId -->
            <if test="memberId != null">
                and member_id in
                 <foreach item="item_member" index="index" collection="memberId" open="(" separator="," close=")">#{item_member}</foreach>
            </if>
            <!-- 手機(jī)號(hào) -->
            <if test="mobile != null">
                and mobile = #{mobile}
            </if>
            <!-- 公司名稱 -->
            <if test="companyName != null">
                and company_name like CONCAT('%',#{companyName},'%')
            </if>
            
            <!-- 公司名稱全稱 -->
            <if test="fullCompanyName != null">
                and company_name = #{fullCompanyName}
            </if>
            <!-- 池類型(1:會(huì)員池,2:客戶池) -->
            <if test="type != null">
                and type = #{type}
            </if>
            <!-- 起始時(shí)間 -->
            <if test="startPoolCreate != null">
                and pool_create &gt;= #{startPoolCreate}
            </if>
            <!-- 結(jié)束時(shí)間 -->
            <if test="endPoolCreate != null">
                and pool_create &lt;= #{endPoolCreate}
            </if>
        </trim>
    </sql>

<select id="query" parameterType="com.wuage.clm.param.ClmPoolParam"
        resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from clm_pool
        <where>
            <include refid="param_where_query" />
        </where>
        order by id desc
        limit #{startNum}, #{pageSize}
    </select>
    
入?yún)⒌念愋椭械臅r(shí)間處理
圖片.png

4.2查詢出數(shù)據(jù)后的根據(jù)count進(jìn)行分頁(yè)

                    int totalPage =0,pageSize=10;
                    int count= clmCirculationRes.getCount();
                    totalPage = (count+ pageSize - 1) / pageSize;
最后編輯于
?著作權(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),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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