在
mybatis的开发实践中,有遇到if标签中判断boolean类型的问题,网上搜索的结果有说判断是否为null,有说用choose标签,感觉乱七八糟,所以写下这篇记录下来。
- 代码
//mapper中的代码
public interface HouseTypeMapper extends BaseMapper<HouseType> {
List<HouseType> queryHouses(@Param("isCity") Boolean isCity);
}
//xml中的代码
<select id="queryHouses" resultType="com.xxx.xxx.entity.HouseType">
SELECT * FROM house_type ht
WHERE 1 = 1
<if test="!isCity">
AND ht.covered_area = 5
</if>
</select>
- 打印的
SQL结果:
-
isCity == false
SELECT * FROM house_type ht WHERE 1 = 1 AND ht.covered_area = 5 -
isCity == true
SELECT * FROM house_type ht WHERE 1 = 1
- 结论:
在if标签里直接判断(<if test="isCity"> <if test="!isCity">)就可以了