1.问题描述

我对user表进行一个分页+条件查询,xml写的是

    <!-- 查询用户列表 -->
    <select id="selectUserList" parameterType="com.ruoyi.entity.user.User" resultType="com.ruoyi.entity.user.User">
        SELECT * FROM user
        <where>
            <if test="username != null">AND username = #{username}</if>
            <if test="phone != null">AND phone = #{phone}</if>
            <if test="status != null">AND status = #{status}</if>
        </where>
    </select>

前端我空传一个user的情况下(也就是根本没限定条件,理应返回整个user表)居然出现了差不到数据

User(id=null, username=, password=, phone=, realName=, idCard=, faceUrl=, isVerified=null, inviterId=null, inviteCode=, inviteCount=null, totalRewardTomato=null, tomatoCount=null, status=null, createTime=null, updateTime=null, tags=, commissionRate=null, commissionRateFather=null, serviceFee=null, withdrawFee=null, membershipFee=null, totalCommission=null)

2.问题追溯

我用插件看了一下执行的sql

SELECT count(0) FROM user WHERE username = '' AND phone = ''

找到原因了,空字符串,mybatis会把其视为有效值,只有null才会被无视掉

3.解决--

- 在 MyBatis 的 SQL 查询中,使用 IS NULL 来处理 null 值,而不是直接比较:

     <select id="selectUserList" parameterType="com.ruoyi.entity.user.User" resultType="com.ruoyi.entity.user.User">
       SELECT * FROM user
       <where>
           <if test="username != null and username != ''">AND username = #{username}</if>
           <if test="phone != null and phone != ''">AND phone = #{phone}</if>
           <if test="status != null">AND status = #{status}</if>
       </where>
   </select>

对于字符串,我们不仅仅是判断是否是null,还需要排除空字符串情况