mybatis Integer类型查询可能出现的问题

本文探讨了在MyBatis中使用mapper.xml进行复杂条件查询时的优化技巧,特别是针对状态值包含0的情况,提供了两种if标签的使用方法,避免了将0误判为空字符串的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mapper.xml :

<select id="count" parameterType="com.pinyu.system.web.page.Page" resultType="java.lang.Integer">
		select count(m.id) from hr_push_msg_model as m
		<where>
			<if test="page.keyword != null and page.keyword != ''">
				m.text like '%${page.keyword}%'
			</if>
			<if test="page.entity != null">
				<if test="page.entity.text != null and page.entity.text != ''">
					and  m.text like '%${page.entity.text}%'
				</if>
				<if test="page.entity.title != null and page.entity.title != ''">
					and  m.title like '%${page.entity.title}%'
				</if>
				<if test="page.entity.state != null and page.entity.state != ''">
					and  m.state = #{page.entity.state}
				</if>
				<if test="page.entity.type != null and page.entity.type != ''">
					and  m.type = #{page.entity.type}
				</if>
			</if>
		</where>
	</select>

比如

<if test="page.entity.state != null and page.entity.state != ''">
                    and  m.state = #{page.entity.state}
                </if>

当state这个值为0的时候,mybatis为默认为空字符串"",所以如果状态这种类似的场景有0值得,查询就不要加上xxxx!=""这种。或者or xxx==0

代码示例:

1、

<if test="page.entity.state != null">
     and  m.state = #{page.entity.state}
</if>

2、

<if test="page.entity.state != null and page.entity.state != '' or page.entity.state==0">
    and  m.state = #{page.entity.state}
</if>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值