大家好,我是书架呀。
在前两节的内容中,主要介绍了Mybatis框架依据Dao层接口、映射文件(写SQL语句的Mapper.xml文件)、配置文件SqlMapConfig.xml完成基本的增删改查工作。
这节内容书架将深入映射文件,介绍动态SQL。动态SQL的引入是为了解决复杂业务场景下,更好地控制传入参数对于SQL语句的影响。
项目的运行环境仍然采用【Mybatis】快速搭建01,这里不再赘述。
2.动态SQL-if
第一个运用在动态SQL中的法宝是if标签,通常用于where语句中,if主要用来做判断。
通过判断参数值是否满足某个条件来决定是否使用该参数作为查询条件,它也经常用于update语句中判断是否更新某一个字段,还可以在insert语句中用于判断是否插入某个字段的值。
下面逐一介绍上述三个场景。
2.1 查询语句where中使用if
为了更好的理解如何在where中引入if标签,我们先引入一个普通的实例。根据用户的id、username、password查出用户的记录。
Dao层接口UserMapper增加findByCondition方法。
public User findByCondition(User user);
映射文件UserMapper.xml中增加
<select id="findByCondition" resultType="com.zssj.domain.User">
select * from user where id = #{id} and username = #{username} and password = #{password}
</select>
测试类中的测试代码
@Test
public void test6() throws IOException {
//1. 读取核心配置文件SqlMapConfig.xml
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2. 创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(in);
//3. 使用工厂生产一个SqlSession对象
SqlSession session = factory.openSession();
//4. 使用SqlSession创建Dao接口的代理对象
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = new User();
user.setId(6);
user.setUsername("caocao");
user.setPassword("hello123");
User byIdTest = userMapper.findByCondition(user);
System.out.println(byIdTest);
//5. 释放资源
session.close();
in.close();
}
在这个示例中,测试方法生成User对象id值为6,username为caocao,password为hello123。
因此在UserMapper.xml的查询语句中这