Mybatis 拼接语句 区分 空,false,true

背景:

最近在写毕设,有一个歌曲展示模块,包含全部歌曲、已通过歌曲、未通过歌曲,点击不同的模块,根据条件筛选歌曲,展示相应的内容。如图 歌曲实体类有个属性值songState来标识歌曲是否通过审核


出错

    本意:songState为null,查询全部;为false或true,查询 ‘不通过’ 或 ‘通过’ 的歌曲。 这样写出错, songState为false与为null时,查询出的结果是一样的。
<!--Singer querySingerAllInfoById(int singerId,Boolean songState);-->
  <select id="querySingerAllInfoById" resultMap="SingerSongMap">
        select *
        from singer
        left join song on singer.singerId = song.singerId
        where singer.singerId =#{singerId}
        <if test="songState != null">
            and songState = #{songState}
        </if>
    </select>

原因: 查询网上资料,说是因为 if动态拼接时 false 值会被转换为null。即false等同于null。所以查不出 songState为false的歌曲。


解决方法

<!--Singer querySingerAllInfoById(int singerId,Boolean songState);-->
    <select id="querySingerAllInfoById" resultMap="SingerSongMap">
        select *
        from singer
        left join song on singer.singerId = song.singerId
        where singer.singerId =#{singerId}
        <choose>
            <when test="songState != null">
                and songState = #{songState}
            </when>
        </choose>
    </select>

(这样写能区分 false null true) 来回试就解决了,具体为啥,俺也不清楚。 就先这样!

经验分享 程序员 微信小程序 职场和发展