MyBatis 动态 SQL 中 <choose> 标签详解
MyBatis 动态 SQL 中的 <choose> 标签类似于 Java 中的 switch 语句,它包含多个 <when> 标签和一个 <otherwise> 标签,用于根据不同的条件执行不同的 SQL 语句,增强 SQL 语句的灵活性。
每个 <when> 标签都有一个 test 属性,用于判断其是否执行。当 <when> 标签的 test 属性为 true 时,执行 <when> 标签中的 SQL 语句,否则执行 <otherwise> 标签中的 SQL 语句。
例如,以下代码展示了如何使用 <choose> 标签根据不同的条件执行不同的 SQL 语句:
<select id="selectUser" resultType="User"><choose>
<when test="name != null and name != ''"><where>
name = #{name}
</where></when>
<when test="age != null"><where>
age = #{age}
</where></when>
<otherwise>
<where>1 = 1</where>
</otherwise>
</choose></select>
这段代码中,如果 name 不为空,则执行第一个 <when> 标签中的 SQL 语句;如果 age 不为空,则执行第二个 <when> 标签中的 SQL 语句;如果 name 和 age 都为空,则执行 <otherwise> 标签中的 SQL 语句。
使用 <choose> 标签可以使 SQL 语句更加灵活,并且可以方便地根据不同的条件执行不同的 SQL 语句。
原文地址: https://www.cveoy.top/t/topic/mS9q 著作权归作者所有。请勿转载和采集!