Mybatis傳遞map參數。


參考文檔:

mybatis之foreach使用方式

第一種方式-mapper接口沒有使用@Param("keyName")來設置鍵:

mybatis更新sql語句:

<update id="updateUsers" parameterType="Map">
update user
set update_time  = ${updateDate},
    opetation_id = ${updateUser}
where id in
<foreach collection="userIds" item="id" separator="," open="(" close=")">
  ${id}
</foreach>
</update>

在mapper接口沒有使用@Param("keyName")來設置鍵的情況下,foreach標簽的collection取的是傳遞過來的map中的key值;若是傳遞的是List集合,mybatis底層默認構建的map的key值為“list”;若傳遞的是array數組,mybatis底層默認構建的map的key為“array”。

傳入map參數類型:

map的value類型最好是object,比如limit語句使用的參數為int類型,此時value類型是object,使用#{}方式則會傳入int類型,否則sql會報錯。

HashMap<String,Object> map = new HashMap<String, Object>();
map.put("updateDate", "2021-1-1");
map.put("updateUser", "3");
String[] ids = {"1","2"};
map.put("userIds", ids );

第一種方式-mapper接口使用@Param("keyName")來設置鍵:

mapper接口:

List<User> findUsers(@Param("params") Map<String, Object> map);

mybatis查詢sql語句:

<select id="findUsers" parameterType="Map" resultType="cn.com.xx.entity.User">
select * from user
        where 1=1 
        <if test="params.userName!=null and params.userName!=''">
            and user_name like '%${params.userName}%'
        </if>
        <if test="params.userIds!=null and params.userIds.size() > 0">
           and id in
        <foreach collection="params.userIds" item="id" separator="," open="(" close=")">
              ${id}
        </foreach>
        </if>
</select >

傳入map參數類型:

map的value類型最好是object,比如limit語句使用的參數為int類型,此時value類型是object,使用#{}方式則會傳入int類型,否則sql會報錯。

HashMap<String,Object> map = new HashMap<String, Object>();
map.put("userName", "張三");
String[] ids = {"1","2"};
map.put("userIds", ids );


免責聲明!

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



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