动态sql
sql的内容是变化的,可以根据条件获取到不同的sql语句,主要是where部分发生变化
动态sql的实现,使用的是mybatis提供的标签:<if> <where> <foreach>
动态SQL之<if>
语法
<if test="判断java对象的属性值">
部分sql语句
</if>
使用示例
<select id="selectUserIf" resultType="com.itheima.domain.User">
select * from user
where 1=1
<if test="username != null and username != ''">
username=#{username}
</if>
<if test="id > 0">
and id=#{id}
</if>
</select>
为什么要在where后面加上1=1,这是因为当第一个if中的条件不满而第二个if条件满足的时候,这个时候查询语句会变成如下
select * from user where 1=1 and id=#{id}
如果没在where后面加上1=1,这是因为当第一个if中的条件不满而第二个if条件满足的时候,这个时候查询语句会变成如下
select * from user where and id=#{id}
这种情况下sql语句就会报错
动态SQL之<where>
用来包含多个<if>的,当多个if有一个成立的,<where>会自动增加一个where关键字的,并去掉多余的and,or等。
使用示例
<select id="selectUserWhere" resultType="com.itheima.domain.User">
select * from user
<where>
<if test="username != null and username != ''">
username=#{username}
</if>
<if test="id > 0">
and id=#{id}
</if>
</where>
</select>
动态SQL之<foreach>
循环java中的数组、list集合的,主要用在sql的in语句中。
1)循环list集合中的简单类型
前提接口中方法为:
List<User> selectForeachOne(List<Integer> idList);
mapper文件中的配置:
<select id="selectForeachOne" resultType="com.itheima.domain.User">
select * from user where id in
<foreach collection="list" item="myid" open="(" close=")" separator=",">
#{myid}
</foreach>
</select>
colleaction:表示接口中方法参数的类型,如果是数组使用array,如果是list集合使用list
item:自定义,表示数组和集合成员的变量
open:循环开始时的字符
close:循环结束时的字符
separator:集合成员之间的分隔符
也可以下成下面的形式
<select id="selectForeachOne" resultType="com.itheima.domain.User">
select * from user where id in(
<foreach collection="list" item="myid" separator=",">
#{myid}
</foreach>
)
</select>
最后拼接出的sql语句:

2)循环list集合中的对象,从对象中取出属性
前提:接口中的方法为
List<User> selectForeachTwo(List<User> idList);
mapper文件中的配置
<select id="selectForeachTwo" resultType="com.itheima.domain.User">
select * from user where id in
<foreach collection="list" item="user" open="(" close=")" separator=",">
#{user.id}
</foreach>
</select>
最后拼接出的sql语句:

动态SQL之代码片段
sql代码片段,主要就是复用一些语句
步骤:
1、先使用<sql id="自定义名称唯一"> sql语句,表名,字段等</sql>
<!-- 定义sql的片段-->
<sql id="userSql">
select * from user
</sql>
2、再使用,<include refid="id的值" />
<select id="selectForeachOne" resultType="com.itheima.domain.User">
<include refid="userSql"/>
where id in(
<foreach collection="list" item="myid" separator=",">
#{myid}
</foreach>
)
</select>
MyBatis动态SQL的使用
本文介绍了MyBatis中动态SQL的实现。动态SQL可根据条件获取不同语句,主要是where部分变化。使用<if>、<where>、<foreach>等标签实现,还介绍了代码片段复用语句的方法,同时给出了各标签的语法和使用示例。

被折叠的 条评论
为什么被折叠?



