Mybatis中使用循環遍歷


Mybatis中傳參數的方法

1.使用注解綁定,mapper.xml 對應方法 不需要指定 parameterType,(推薦使用注解綁定方式)

方法接口:

List<CalculateIdeacommissionsum> selectByExample(@Param("example") CalculateIdeacommissionsum example,@Param("roleNameList") List<String> roleNameList);

方法對應的Mapper.xml

<!--  通過userStatus 排序查詢 升序    -->
<select id="selectByExample" resultMap="BaseResultMap">
select
id, calculateYear, calculateMonth, userId, userCode, userName, userStatus, companyName,
companyId, curDeptId, curDeptName, roleName from Calculate_IdeaCommissionSum
where calculateYear=#{example.calculateYear,jdbcType=SMALLINT}
and calculateMonth=#{example.calculateMonth,jdbcType=SMALLINT}
and deleteFlag=#{example.deleteFlag,jdbcType=TINYINT}
<if test="roleNameList!=null and roleNameList.size()&gt; 0">
<foreach collection="roleNameList" item="rolename" separator="," open="and rolename in(" close=")">
#{rolename,jdbcType=VARCHAR}
</foreach>
</if>
order by userStatus
</select>
2.如果接口參數沒有使用注解綁定,mapper.xml 對應方法 需要指定對應的參數類型。

List<CalculateIdeacommissionsum> selectByExample(CalculateIdeacommissionsum example);

方法對應的Mapper.xml

<!--  通過userStatus 排序查詢 升序    -->
<select id="selectByExample" parameterType="實體類路徑" resultMap="BaseResultMap">
select
id, calculateYear, calculateMonth, userId, userCode, userName, userStatus, companyName,
companyId, curDeptId, curDeptName, roleName from Calculate_IdeaCommissionSum
where calculateYear=#{calculateYear,jdbcType=SMALLINT}
and calculateMonth=#{calculateMonth,jdbcType=SMALLINT}
order by userStatus
</select>

3. parameterType 也可以使用Map存放參數進行查詢

接口方法:

List<BaseEmpinfo> selectByParam(Map<String,String> map);

接口方法對應的Mapper.xml 文件方法:

<select id="selectByParam" parameterType="java.util.Map" resultType="com.pacific.rspBonus.model.po.twBonus.mbg.BaseEmpinfo">
select * from Base_EmpInfo
where deleteFlag=0
<if test="userName != null and userName!=''">
and userName=#{userName,jdbcType=VARCHAR}
</if>
</select>
4.mybatis 遍歷循環
collection標識我們程序傳值過來的集合
open表示我們遍歷的集合以什么字符開始
close表示我們遍歷的集合以什么字符結尾
item是給我們集合遍歷取一個變量
separator 表示的是分隔符,將我們集合中遍歷出來的數據用","分隔開。
<if test="roleNameList!=null and roleNameList.size()&gt; 0">
<foreach collection="roleNameList" item="rolename" separator="," open="and rolename in(" close=")">
#{rolename,jdbcType=VARCHAR}
</foreach>
</if>
sql如下:

select * from Calculate_IdeaCommissionSum where calculateYear=2019 and calculateMonth=2 and roleName  in ('副總經理','總監','經紀人');

將roleName的多個條件用關系轉化為 roleName in (roleName1,roleName2,roleName3...)  in中用foreach循環

參考博客:https://jingyan.baidu.com/album/00a07f3873520e82d028dcce.html?picindex=1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM