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  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2021-02-20 C# List LinQ Lambda 表达式
点击右上角即可分享
微信分享提示