动态SQL
mybatis的灵魂是什么?mybatis的灵魂就是动态SQL!
if标签
在映射配置文件中这样写
<select id="findUserByCondition" resultType="com.yixuexi.entity.User" parameterType="com.yixuexi.entity.User">
<!-- 使用if标签 where 1=1不能省略 -->
select * from user where 1 = 1
<if test="name != null">
and name = #{name}
</if>
</select>
- 上面的if 的意思是,如果user对象的name不为空的话 就拼装上 and name = #{name}
- 这里面的if标签,并且的是 and,或者是or
- 如果有多个条件可以拼装多个if标签
- test 的name就是 user对象的name属性。
多个if标签
select * from user where 1 = 1
<if test="name != null">
and name = #{name}
</if>
<if test="password != null">
and password = #{password}
</if>
注意事项:
- 单独使用if标签的时候 一定要添加 where 1=1
- 多个if都会执行
where标签
- 使用where标签就可以省略 where1 = 1了
- 就是在if标签外面套一层where标签 包裹起来
<select id="findUserByCondition" resultType="com.yixuexi.entity.User" parameterType="com.yixuexi.entity.User">
select * from user
<where>
<if test="name != null">
and name = #{name}
</if>
<if test="password != null">
and password = #{password}
</if>
</where>
</select>
很简单,就是添加了一层 where标签
foreach标签
<select id="findUserByIds" parameterType="com.yixuexi.entity.QueryVoIds" resultType="com.yixuexi.entity.User">
select * from user
<where> <!--添加了where之后 就不用再手写 where 1=1 -->
<!--如果这个对象里面的list集合不是null,并且 list集合的个数大于0个 则遍历 -->
<if test="list != null and list.size > 0">
<foreach collection="list" open="and id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
标签内容详解:
- collection:遍历哪个集合,集合名称
- open:开头添加什么 添加 and id in(
} open哪里加and是因为 where标签会帮你加 where 1=1 不加and不行
- close:在结尾添加什么 添加 )
- item:(起个名)把遍历出来的每一项添加到 open和close之间,用,进行分割
- separator:用什么进行分割
- #{id}:item起的什么名字 这里就用什么名字
- 最后拼装出来的sql: select * from user wherer 1 = 1 and id in (1,2,3,4,5)
下一篇更新:mybatis多表查询, 一对一查询