MyBatis SQL語句操作Mysql

來源:互聯網
上載者:User

標籤:ted   param   rtti   line   art   cte   tac   sof   html   

本文記錄使用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

 

MyBatis SQL語句操作Mysql

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.