mybatis传递多个不同类型的参数到mapper xml文件
在业务中查询某张表时需要设置多个查询条件,并且还要根据id列表进行权限过滤,这时推荐采用Map<String, Object>作为参数进行查询,因为:Object可以设置成不同的类型,比如:List<Integer> ids, Map<String, Object>
我们看一个例子:
<select id="getByParam" resultMap="CrowdManageResult" parameterType="java.util.Map">select <include refid="Base_Column_List"/>from t_crowd_manage where 1=1<if test="crowd.name != null">and name like concat('%',#{crowd.name, jdbcType=VARCHAR},'%')</if><if test="crowd.type != null">and type = #{crowd.type, jdbcType=INTEGER}</if><if test="crowd.status != null">and status = #{crowd.status, jdbcType=INTEGER}</if><if test="crowd.noStatus != null">and status != #{crowd.noStatus, jdbcType=INTEGER}</if><if test="ids != null and ids.size() > 0">and id in<foreach item="id" collection="ids" open="(" separator="," close=")">#{id, jdbcType=BIGINT}</foreach></if>order by update_time desc
</select>
service层查询代码:
Map<String, Object> param = new HashMap<>(2);
Map<String, Object> crowdEntity = new HashMap<>(); // xml if 判断不会报错
crowdEntity.put("name", "test");
crowdEntity.put("type", 1);
crowdEntity.put("noStatus", -1);Set<Integer> idList = //....param.put("crowd", crowdEntity);
param.put("ids", idList);
注意:这个sql条件查询条件主要设计两个部分:
- 一般的查询条件,这里可以使用Bean对象,也可以使用map。推荐使用后者,因为在sql的条件中有一个noStatus字段判断,通常Bean定义的时候只有status字段(没有noStatus),如果这里使用定义Bean来当查询参数,在xml中<if test="crowd.noStatus != null"> 这句会报错。原因是mybatis的xml采用ONGI查询来解析,所以如果Bean中没有定义这个字段,就会报错。
- in条件查询,这里使用的是foreach