上一节我们介绍的where标签可以帮助我们去掉标签前多余的and或者or,但是不能去掉标签后的and/or, 本节我们介绍的trim标签可以帮助我们解决这个问题。
目录
1.trim标签属性介绍
prefix | 将trim标签前添加指定内容 |
prefixOverrides | 将trim标签前去掉指定内容 |
suffix | 将trim标签后添加指定内容 |
suffixOverrides | 将trim标签后去掉指定内容 |
2. mapper接口不变
/**
* 多条件查询员工信息
*/
List<Emp> getEmpByCondition(Emp emp);
3. mapper映射文件
prefix = where : 在语句前添加where
suffixOverrides = "and|or : 在语句后删除and或者or
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp
<trim prefix="where" suffixOverrides="and|or">
<if test="empName != null and empName != ''">
emp_name = #{empName} and
</if>
<if test="age != null and age != ''">
age = #{age} or
</if>
<if test="sex != null and sex != ''">
and sex = #{sex} and
</if>
<if test="email != null and email != ''">
and email = #{email}
</if>
</trim>
</select>
4. 参数有内容时
@Test
public void testGetEmpByCondition(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSqlMapper mapper = sqlSession.getMapper(DynamicSqlMapper.class);
List<Emp> emps = mapper.getEmpByCondition(new Emp(null, "张三", 32, null, null));
System.out.println(emps);
}
4.1 测试结果
我们从LOG中可以看到,trim标签有内容时候,执行了传入参数的条件,添加了需要的where,并且去掉了多余的and和or.
15:11:11:320 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource 434 - Created connection 1787079037.
15:11:11:335 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==> Preparing: select * from t_emp where emp_name = ? and age = ?
15:11:11:382 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==> Parameters: 张三(String), 32(Integer)
15:11:11:413 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - <== Total: 1
[Emp{eid=1, empName='张三', age=32, sex='男', email='123@qq.com', dept=null}]
5. 参数无内容时
List<Emp> emps = mapper.getEmpByCondition(new Emp(null, null, null, null, null));
5.1 测试结果
我们从log中看出,where后的条件就没有执行,只执行了where之前的。
5:13:54:089 [main] DEBUG org.apache.ibatis.datasource.pooled.PooledDataSource 434 - Created connection 1787079037.
15:13:54:089 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==> Preparing: select * from t_emp
15:13:54:120 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - ==> Parameters:
15:13:54:151 [main] DEBUG org.apache.ibatis.logging.jdbc.BaseJdbcLogger 137 - <== Total: 5
[Emp{eid=1, empName='张三', age=32, sex='男', email='123@qq.com', dept=null}, Emp{eid=2, empName='李四', age=23, sex='女', email='1234@qq.com', dept=null}, Emp{eid=3, empName='王五', age=35, sex='男', email='12345@qq.com', dept=null}, Emp{eid=4, empName='赵六', age=56, sex='女', email='123456@qq.com', dept=null}, Emp{eid=5, empName='田七', age=43, sex='男', email='1234567@qq.com', dept=null}]
6.总结
trim标签
trim标签有内容时:
1. prefix/ suffix 在标签前/后添加指定内容
2. prefixOverrides/ suffixOverrides 在标签后删除指定内容
trim标签无内容时:trim标签没有任何效果,只执行标签前的语句,如select * from t_emp