1.1 动态SQL概述
传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误。Mybatis的动态SQL功能正是为了解决这种问题, 其通过 if,foreach,where, set等标签,可组合成非常灵活的SQL语句,从而提高开发人员的效率。接下来我们重点解析两个标签,if和foreach。
1.2动态SQL之<if>
我们根据实体类的不同取值,使用不同的 SQL语句来进行查询。比如在 id如果不为空时可以根据id查询,如果username 不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。
接下来我们看一个例子,这是一个通过条件查询的语句
<select id="findByCondition" parameterType="User" resultType="User">
select * from tb_user
<where>
<if test="id!=0">
and id= #{id}
</if>
<if test="username!= null">
and username = #{username}
</if>
<if test="password!=null">
and password = #{password}
</if>
</where>
</select>
我们添加测试类进行测试
@Test
public void test01() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setId(3);
user.setUsername("wwb");
//user.setPassword("520");
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.findByCondition(user);
sqlSession.close();
System.out.println(userList);
}
看控制台输出
可以看到,就算我们在select查询语句中定义了三个查询条件,但使用if标签时,程序会根据我们提供的条件去查询,避免了之前需要三个条件才能查询成功的约束。
当只有id存在时,我们再看一下控制台输出
1.3动态SQL之<foreach>
foreach主要时循环执行sql的拼接操作。例如我们想查询如下语句
select * from tb_user where id in(1,2,3,4)
实际开发中,我们要根据用户传递的参数进行查询,此时我们就需要使用数组或者集合来接收,然后使用foreach标签来遍历集合或数组。
<!-- foreach 里面的collection如果是集合就写list,数组就写array,不然会报错-->
<select id="findByIds" resultType="user" parameterType="arraylist">
select * from tb_user
<where>
<foreach collection="list" open="id in (" close=")" separator="," item="id">
#{id}
</foreach>
</where>
</select>
dao接口:使用集合存储数据
public List findByIds(ArrayList ids);
这里的标签需要解释一下:
标签属性:
collection:表示循环的对象是数组还是list集合。如果dao方法的形参是数组,collection=“array”;如果dao方法形参是list,collection=“list”;
open:循环开始的字符。sql.append(“id in(”);
close:循环结束的字符。sql.append(")");
item:集合成员,自定义的变量。
separator:集合成员之间的分隔符。sql.append(",");
#{item的值}:获取集合成员的值;
接下来我们添加测试
@Test
public void test02() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(1);
arrayList.add(3);
arrayList.add(4);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.findByIds(arrayList);
System.out.println(users);
}
看控制台输出
可以看出,根据我们提供的集合去遍历表中的数据,从而取出符合条件的数据集。