Fork me on GitHub

MyBatis中的动态sql


动态sql
if 做判断拼接sql语句
choose,when 类似于Java的switch判断
set 修改语句专用,可以自动排错,比如多写了逗号
sql,include 用于提取重复的语句,提高复用
foreach 用于动态的查询多条信息
<!--if-->
<select id="getBlogBy">
SELECT * FROM blog
<where>
<if test="title != null">
`title` LIKE #{title}
</if>
<if test="author != null">
and author like #{author}
</if>
</where>
</select>

<!--choose,when-->:
<select id="getBlogBy2">
select * from blog
<where>
<choose>
<when test="title != null">
`title` LIKE #{title}
</when>
<when test="author != null">
and author like #{author}
</when>
<when test="views != null">
and views >= #{views}
</when>
<otherwise>
1=1
</otherwise>
</choose>
</where>
</select>

<!--sql,include-->:
<sql id="gerontology">
<if test="title != null">
`title` LIKE #{title}
</if>
<if test="author != null">
and author like #{author}
</if>
</sql>
<!--查询全部-->
<select id="getBlogBy">
SELECT * FROM blog
<where>
<include refid="gerontology"/>
</where>
</select>

<!--foreach-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>

posted @ 2024-03-16 22:40  一名狗书匠&  阅读(2)  评论(0编辑  收藏  举报

asd