MyBatis SQL语句操作Mysql

本文记录使用Mybatis操作数据库时碰到的一些语句,供以后参考。

 

一,多条件查询

示意SQL语句:SELECT t_field1, t_field2 FROM table_name WHERE t_field3 (BETWEEN startTime AND endTime) AND t_field4 IN (xxx,xxx,xxx)

Mapper接口配置:

    public List<Chat> query(@Param("startTime") long startTime, @Param("endTime") long endTime, @Param("sids") List<Long> sidList);

 

Mapper.xml配置:

    <select id="query" resultMap="chat">
        SELECT uid,content from tableName
        WHERE
        ( UNIX_TIMESTAMP(data_time) >= #{startTime} ) AND ( UNIX_TIMESTAMP(data_time) &lt;= #{endTime} )
        AND sid IN
        <foreach collection="sids" item="item" index="index" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

 

resultMap 将数据库中的列名 与 JavaBean 属性名 对应,从而映射成Java对象。Chat则是一个拥有两个字段(uid 和 content)的 JavaBean类。

    <resultMap id="chat" type="Chat"><!-- Chat 是在mybatisConfig.xml中定义的别名(全限定包名在 mybatisConfig.xml中配置了)-->
        <id property="id" column="id"/>
        <result property="uid" column="uid"/>
        <result property="content" column="content"/>
    </resultMap>

 

解释:①Mapper接口中的方法名 与 Mapper.xml中的 <select id 一 一对应。

②Mapper接口 通过 @Param 实现多个参数传递。可参考:MyBatis简单使用和入门理解 中的“使用参数注解的形式传递多个参数”。@Param中指定的参数名称 与 select 查询语句中的 名称 一 一对应。比如:@param("startTime")  对应 #{startTime} 。  @param("endTime")  对应 #{endTime}  。

 @param("sids")  对应 foreach collection="sids"

③通过 foreach 语句,对 sid 字段 实现了 多条件匹配。相当于 sid IN {xxx1,xxx2,xxx3....}

④另外对于数据库中的String类型 data_time字段,首先转化成UNIX时间戳,然后与 startTime 及 endTime 比较。注意的是 <= 是用 &lt; 来表示的。否则会报下面错误

tag name are expected

 

posted @ 2017-09-02 12:57  大熊猫同学  阅读(2625)  评论(0编辑  收藏  举报