mybatis动态SQL之if标签

mybatis动态SQL之if标签

我们根据实体类的不同取值,使用不同的 SQL 语句来进行查询。比如在 id 如果不为空时可以根据 id 查询,如果 username 不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。

1、持久层接口

/**
* 根据用户信息,查询用户列表
* @param user
* @return
*/
List<User> findByUser(User user);

2、映射配置

<!--参数类型和返回值结果类型使用了别名-->
<select id="findByUser" resultType="user" parameterType="user">
    select * from user where 1=1
    <if test="username!=null and username != '' ">
   	 and username like #{username}
    </if> 
    <if test="address != null">
    	and address like #{address}
    </if>
</select>

注意:if标签的 test 属性中写的是对象的属性名,如果是包装类的对象要使用 OGNL 表达式的写法。另外要注意 where 1=1 的作用~!

3、测试

@Test
public void testFindByUser() {
    User u = new User();
    u.setUsername("%王%");
    u.setAddress("%顺义%");
    //6.执行操作
    List<User> users = userDao.findByUser(u);
    for(User user : users) {
    System.out.println(user);
	} 
}
记得快乐
原文地址:https://www.cnblogs.com/Y-wee/p/13835094.html