拼接SQL语句字符串
1、标签
public interface DynamicSQLMapper {
// 多条件查询
List<Emp> getEmpByCondition(Emp emp);
}
使用1=1在个别参数不符合时,进行连接,跳过
<!--List<Emp> getEmpByCondition(Emp emp); 1=1 拼接后面条件 -->
<select id="getEmpByCondition" resultType="Emp">
select * from t_emp where 1=1
<if test="empName != null and empName !=''">
emp_name = #{empName}
</if>
<if test="age != null and age !=''">
and age = #{age}
</if>
<if test="sex != null and sex !=''">
and sex = #{sex}
</if>
<if test="email != null and email !=''">
and email = #{email}
</if>
</select>
@Test
public void testGetEmpByCondition(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
// List<Emp> list = mapper.getEmpByCondition(new Emp(null, "张三", 23, "男", "123@qq.com"));
// List<Emp> list = mapper.getEmpByCondition(new Emp(null, "张三", null, "男", "123@qq.com"));
List<Emp> list = mapper.getEmpByCondition(new Emp(null, null, 23, "男", "123@qq.com"));
System.out.println(list);
}
2、where标签
(1)当where标签中有内容时,会自动生成where关键字,并且将内容前多余的and 或 or 去掉
(2)当where标签中没有内容时,此时where标签没有任何效果
注意:where标签不能将其中内容后面多余的and或or去掉
<!--List<Emp> getEmpByCondition(Emp emp); 1=1 拼接后面条件 -->
<select id="getEmpByCondition