Mybatis中的 switch

我这遇到个问题,如果 type字段为null则查询type is null,否则查对应的值
询问 AI 得知,可以用choose-when-otherwise

<select>
select * from user
<where>
<choose>
<when test="type != null">and type = #{type}</when>
<otherwise>and type is null</otherwise>
</choose>
</where>
</select>

AI 给出的例子,登录账户时使用username 或者email 或者 手机号

<select id="selectUser" parameterType="map" resultType="com.example.User">
SELECT * FROM users
WHERE
<choose>
<when test="username != null and username != ''">
username = #{username}
</when>
<when test="phone != null and phone != ''">
phone = #{phone}
</when>
<otherwise>
email = #{email}
</otherwise>
</choose>
</select>

似乎when可以有很多个并排,但是我没有测试



这是mybatis官方的例子,官网把choose-when-otherwise比作Java的switch-case语句

Sometimes we don’t want all of the conditionals to apply, instead we want to choose only one case among many options. Similar to a switch statement in Java, MyBatis offers a choose element.

Let’s use the example above, but now let’s search only on title if one is provided, then only by author if one is provided. If neither is provided, let’s only return featured blogs (perhaps a strategically list selected by administrators, instead of returning a huge meaningless list of random blogs).

<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>

突然发现我那个也可以改成

<if test="type == null"> and type is null</if>
<if test="type != null and type != ''"> and type = #{type}</if>

Mybatis 没有if-else,只有if


__EOF__

本文作者echo_lovely
本文链接https://www.cnblogs.com/echo-lovely/p/18726475.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   echo_lovely  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2021-02-20 C# List LinQ Lambda 表达式
点击右上角即可分享
微信分享提示