【mybatis mapper XML】List类型入参参数处理
生活随笔
收集整理的這篇文章主要介紹了
【mybatis mapper XML】List类型入参参数处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
- mybatis 3.4.6
- 如果 DAO 中這樣傳參,XML該如何處理呢?
XML
<select id="selectLatestArticleList" parameterType="map" resultMap="ArticleResult">select * from article where pubTime >= DATE_FORMAT( NOW() - INTERVAL #{maxDay} DAY, '%Y-%m-%d' ) and channel in <foreach item="item" collection="channelIdList" open="(" separator="," close=")">#{item}</foreach></select>說明:
- collection="channelIdList"中的channelIdList是DAO入參的參數名
- item="item"中的item是本次迭代獲取到的元素的別名。
上面的xml會變成下面的sql:
select * from article where pubTime >= DATE_FORMAT( NOW() - INTERVAL 1 DAY, '%Y-%m-%d' ) and channel in (1,2,3)foreach 介紹
- foreach用于處理動態 SQL 的一個常見使用場景:對集合進行遍歷(尤其是在構建 IN 條件語句的時候)。
- 這里的集合指:可迭代對象(如 List、Set 等)、Map 對象或者數組對象。
- 當使用可迭代對象或者數組時,index 是當前迭代的序號,item 的值是本次迭代獲取到的元素。
- 當使用 Map 對象(或者 Map.Entry 對象的集合)時,index 是鍵,item 是值。
collection 屬性取值的幾種情況
當使用可迭代對象或者數組時,有3種情況:
例子
例子1:
<select id="selectPostIn" resultType="domain.blog.Post">SELECT *FROM POST PWHERE ID in<foreach item="item" index="index" collection="list"open="(" separator="," close=")">#{item}</foreach> </select>例子2:
<insert id="insertAuthor" useGeneratedKeys="true"keyProperty="id">insert into Author (username, password, email, bio) values<foreach item="item" collection="list" separator=",">(#{item.username}, #{item.password}, #{item.email}, #{item.bio})</foreach> </insert>參考
https://mybatis.org/mybatis-3/zh/dynamic-sql.html
https://www.cnblogs.com/fnlingnzb-learner/p/10566452.html
總結
以上是生活随笔為你收集整理的【mybatis mapper XML】List类型入参参数处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL 查看执行计划
- 下一篇: 我妈怎么知道我的开机密码电脑如何查看开机