MyBatis中使用动态SQL类型有两种方式:使用if
元素和使用choose
元素。
if
元素:可以根据条件动态拼接SQL语句。例如:<select id="getUserList" parameterType="map" resultMap="userResultMap">
SELECT * FROM users
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="email != null">
AND email = #{email}
</if>
</where>
</select>
choose
元素:可以根据条件选择不同的SQL语句执行。例如:<select id="getUserList" parameterType="map" resultMap="userResultMap">
SELECT * FROM users
<where>
<choose>
<when test="order == 'asc'">
ORDER BY id ASC
</when>
<when test="order == 'desc'">
ORDER BY id DESC
</when>
<otherwise>
ORDER BY id ASC
</otherwise>
</choose>
</where>
</select>
使用动态SQL类型可以根据不同的条件灵活地构建SQL语句,使查询更加灵活和高效。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:MyBatis中动态SQL怎么使用