Mybatis映射文件深入
1.1动态sql语句
1.动态sql语句概述
开发人员在使用JDBC或其他类似的框架进行数据库开发时,通常都要根据需求去手动拼装SQL,这是一个非常麻烦的工作,而Mybatis提供的对SQL语句动态组装功能,恰能很好的解决这一问题。
2.动态SQL之<if.>
我们根据实体类的不同取值,使用不同的SQL语句来进行查询。比如id如果不为空时可以根据id查询,如果username不为空时还要加入用户名作为条件。where作为标签会动态的出现,当where标签内所有元素都为空时where也不存在,即查询所有记录。
- mapper文件内容
<select id="findByCondition" parameterType="user" resultType="user">
select * from 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>
注意:1.where标签动态出现,当所有条件不存在会where也不会出现
2.where标签会移除多余的and
- mapper接口内容
public interface UserMapper {
public List<User> findByCondition(User user);
public List<User> findByIds(List<Integer> ids);
}
- 测试代码
@Test
public void test1() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
//模拟条件user
User condition = new User();
condition.setId(1);
condition.setUsername("zhangsan");
condition.setPassword("123");
List<User> userList = userMapper.findByCondition(condition);
System.out.println(userList);
}
3.动态SQL之<foreach.>
循环执行sql的拼接操作,例如:SELECT * FROM USER WHERE ID IN(1,2,5)
- mapper文件内容
<select id="findByIds" parameterType="list" resultType="user">
select * from user
<where>
<foreach collection="list" open="id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
注意:1.foreach标签里的属性collection:配置的是传递过来的参数类型(首字母小写),它可以是一个array或list、Map集合的键、POJO包装类中数组或集合类型的属性名
2.item:配置的是循环中当前的元素
3.index:配置的是当前元素在集合的位置下标
4.separator:配置的是各个元素之间的分隔符
5.当使用可迭代对象或者数组时,index是当前迭代次数,item的值是本次迭代获取的元素,当使用字典或者Map Entry对象集合时,index是键,item是值。
- mapper接口方法
public interface UserMapper {
public List<User> findByCondition(User user);
public List<User> findByIds(List<Integer> ids);
}
- 测试代码
@Test
public void test2() throws IOException {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
//模拟ids的数据
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
List<User> userList = userMapper.findByIds(ids);
System.out.println(userList);
}
1.2SQL片段抽取
sql中可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的