版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
mybatis学习笔记(5) ---- 动态Sql
mybatis中的一大特性就是动态sql,在传统的JDBC编程中,根据条件编写,拼接SQL语句很容易出错,因此mybatis引入了动态sql。动态Sql元素和JSTL(jSP标准标签库)很像。动态sql的本质就是对sql进行灵活拼接和组装。
if标签
if标签最常用到,在查询和删除更新数据的时候作判断时结合test属性使用。主要用来判断参数是否合法,如参数不能为null等。
mapper.xml
<select id="find" parameterType="com.excellent.po.User" resultType="com.excellent.po.User">
select * from user
<where>
<if test="user != null">
<if test="user.id != null">
AND id > #{user.id}
</if>
<if test="user.sex != null">
AND sex = #{user.sex}
</if>
</if>
</where>
</select>
test
@Test
public void test6(){
SqlSession sqlSession = factory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setId(10);
user.setSex("1");
List<User> list = mapper.find(user);
for(User user1 : list){
System.out.println(user1);
}
sqlSession.close();
}
foreach标签
顾名思义,这个标签是用来循环遍历的,可以实现多个相同样式条件的查询。
mapper.xml
<select id="findById" parameterType="java.util.ArrayList" resultType="java.util.Map">
<!--
select * from user where id in (1,10,16,22)
collection:指定输入 对象中集合属性
item:每个遍历生成对象中
open:开始遍历时拼接的串
close:结束遍历时拼接的串
separator:遍历的两个对象中需要拼接的串
-->
SELECT *
FROM user
WHERE id in
<foreach item="i" collection="list" open="("
separator="," close=")">
#{i}
</foreach>
</select>
set标签
- mapper.xml
<mapper namespace="com.excellent.mapper.UserMapper">
<insert id="adduser" parameterType="com.excellent.po.User">
update user
<set>
<if test="user.sex != null">
sex = #{user.sex}
</if>
<if test="user.username != null">
and username = #{user.username}
</if>
</set>
where id = #{user.id}
</insert>
Sql片段
将一些常用的,出现几率高的sql语句抽出来,用sql标签封装起来,就像一个函数一样,用的时候,只需要调用即可,无需重写。减少代码冗余。
- mapper.xml
<sql id="mysql1">
select * from user
</sql>
<select id="findAll" resultType="com.excellent.po.User">
<include refid="mysql1"/>
</select>