前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >mybatis常用条件查询总结(迭代一)

mybatis常用条件查询总结(迭代一)

作者头像
挑战者
发布2018-06-29 17:31:25
1.9K0
发布2018-06-29 17:31:25
举报
文章被收录于专栏:java沉淀

目录 1.mybatis中大于等于小于等于的写法 2.mybatis动态查询条件组装 3.mybatis批量条件 4.mybatis时间查询实现分页总结

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

第一种写法(1):

代码语言:javascript
复制
原符号       <        <=      >       >=       &        '        "
替换符号    <    <=   >    >=   &   '  "
例如:sql如下:
create_date_time >= #{startTime} and  create_date_time <= #{endTime}

第二种写法(2):

代码语言:javascript
复制
大于等于
<![CDATA[ >= ]]>
小于等于
<![CDATA[ <= ]]>
例如:sql如下:
create_date_time <![CDATA[ >= ]]> #{startTime} and  create_date_time <![CDATA[ <= ]]> #{endTime}

2.mybatis动态查询条件组装如下:

代码语言:javascript
复制
 <!--  if(判断参数) - 将实体类不为空的属性作为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批量条件

代码语言:javascript
复制
在Mybatis的xml配置中使用集合,主要是用到了foreach动态语句。foreach元素的属性主要有 item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔符,close表示以什么结束。
说明:以下示例关于MySQL数据库。由于**传入的参数是多个**,因此把它们封装成一个Map了,当然单参数也可以用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属性是必须指定的,在不同情况下该属性的值是不一样的:
如上述例子,传入的参数是多个时,collection属性值为传入List或array在**map里面的key**;传入的是单参数且参数类型是List时,collection属性值为list;传入的是单参数且参数类型array时,collection的属性值为array。

3.1mybatis批量插入

代码语言:javascript
复制
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>  

       由于批量增加的方法中参数为List,所以parameterType的值为[Java](http://lib.csdn.net/base/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 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批量删除条件

代码语言:javascript
复制
**批量删除操作步骤**
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>  

由于批量删除的方法中参数为List,所以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批量查询操作步骤

代码语言:javascript
复制
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>  

由于批量查询的方法的返回为List<User>,所以resultType的值为User,即com.mahaochen.mybatis.domain.User。详见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>  
        <!-- 注册实体Bean -->  
        <typeAlias type="com.mahaochen.mybatis.domain.User" alias="User"/>  
</typeAliases>  

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 
    * @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批量更细操作步骤

代码语言:javascript
复制
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需要数据库连接配置&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>  
      
    <!-- 【扩展知识】 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>  

         由于批量更新的方法中参数为List,所以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 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分页查询实现总结

4.1分页实现根据时间的范围

代码语言:javascript
复制
<!-- 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>
            <!-- 手机号 -->
            <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:会员池,2:客户池) -->
            <if test="type != null">
                and type = #{type}
            </if>
            <!-- 起始时间 -->
            <if test="startPoolCreate != null">
                and pool_create &gt;= #{startPoolCreate}
            </if>
            <!-- 结束时间 -->
            <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>
入参的类型中的时间处理

图片.png

4.2查询出数据后的根据count进行分页
代码语言:javascript
复制
                    int totalPage =0,pageSize=10;
                    int count= clmCirculationRes.getCount();
                    totalPage = (count+ pageSize - 1) / pageSize;
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017.08.10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 入参的类型中的时间处理
  • 4.2查询出数据后的根据count进行分页
相关产品与服务
云数据库 MySQL
腾讯云数据库 MySQL(TencentDB for MySQL)为用户提供安全可靠,性能卓越、易于维护的企业级云数据库服务。其具备6大企业级特性,包括企业级定制内核、企业级高可用、企业级高可靠、企业级安全、企业级扩展以及企业级智能运维。通过使用腾讯云数据库 MySQL,可实现分钟级别的数据库部署、弹性扩展以及全自动化的运维管理,不仅经济实惠,而且稳定可靠,易于运维。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档