Explanation of Map Parameters of mybatis Dynamic sql

  • 2021-07-10 19:58:31
  • OfStack

Map Parameters of mybatis Dynamic sql

Mapper file:


<mapper namespace="com.cn.shoje.oa.modules.logistics.dao.PurcDao">
 <select id="findAll" parameterType="Map" resultType="Purchase">
 select * from prod_purchase where 1=1
 <if test="purc_id!=''"> and purc_id=#{purc_id}</if>
 <if test="prod_id!=''"> and prod_id=#{prod_id}</if>
 <if test="ch_id!=''"> and ch_id=#{ch_id}</if>
 <if test="ch_name!=''"> and ch_id in ( select ch_id from channel where ch_name
  like '%#{ch_name}%')</if>
 <if test="purc_time!=''"> and purc_time=#{purc_time} order by #{purc_time} desc
 </if>
 </select>
</mapper>

The value of key in map can be obtained without adding value characters such as # and $in test expression, while the value of key in map can be obtained by writing directly like this, while in other places, it is necessary to have # {key in map} to obtain the value of key in map

<pre name="code" class="html">

The map parameter passed to mybatis in the background, don't delve into the function meaning, it is enough to know that the following map is finally passed to parameterType in mybatis


public Map<String,String> parseMap(HttpServletRequest req){
 Map<String,String> map=new HashMap<String,String>();
 map.put("prod_id", prod_id);
 map.put("purc_id", purc_id );
 map.put("ch_name", ch_name );
 map.put("ch_id", ch_id);
 map.put("purc_time", purc_time);
 return map;
}

Mybatis Pass in parameter type Map

Mode 1:

mybatis Updates the sql statement:


<update id="publishT00_notice" parameterType="Map">
update test 
set createdate = #{createdate},
creator = #{creator}
where id in 
<foreach collection="ids" item="ids" separator="," open="(" close=")">
#{ids}
</foreach>
</update>

Passed in map parameter type:


HashMap<String,Object> map = new HashMap<String, Object>();
map.put("creator", "creator");
map.put("createdate", "createdate");
String[] ids = {"1","2"};
map.put("ids", ids );

Mode 2:

Step 1 Write on your mapper:


List<WeixinUserLocationList> findweixinUserLocations(@Param("params") Map<String, Object> map);

Note that this is the annotation @ param, which belongs to mybatis

Then write this in xml:


<if test="params.accountId!=null">
      and a.accountid=#{params.accountId}
    </if>
    <if test="params.nickname!=null and params.nickname !=''">
      and a.nickname like '%${params.nickname}%'
    </if>
    <if test="params.beginDate!=null and params.beginDate!=''">
      and date_format(a.createtime,'%Y-%m-%d')>=${params.beginDate}
    </if>
    <if test="params.endDate!=null and params.endDate!=''">
    <![CDATA[  and date_format(a.createtime,'%Y-%m-%d')<=${params.endDate} ]]>   
    </if>

${params. nickname} is written as a string by default, and # {params. accountId} can take Long, Integer and so on.

Summarize


Related articles: