OGNL
if
要求:查询员工,要求,携带了哪个字段查询条件就带上这个字段的值
//携带了哪个字段查询条件就带上这个字段的值public List<Employee> getEmpsByConditionIf(Employee employee);
<!-- public List<Employee> getEmpsByConditionIf(Employee employee);-->
<select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">select * from tb1_employeewhere<!--test,判断表达式(OGNL)OGNL参照PPT或者官方文档c:if test从参数中取值进行判断遇见特殊符号应该去写转义字符;--><if test = "id!=null">id = #{id}</if><if test = "lastName!=null && lastName!=""">and last_name like #{lastName}</if>
<if test="email!=null and email.trim()!=""">and email = #{email}
</if><!--ognl会进行字符串与数字的转换判断 "0"==0 -->
<if test="gender==0 or gender==1">and gender = #{gender}</if></select>
@Testpublic void test04() throws IOException {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();SqlSession sqlSession = sqlSessionFactory.openSession();try{EmployeeMapperDynamicSQL mapper = sqlSession.getMapper(EmployeeMapperDynamicSQL.class);Employee employee = new Employee(3,"%e%","jerry@qq.com",null);List<Employee> emps = mapper.getEmpsByConditionIf(employee);for (Employee emp:emps){System.out.println(emp);}}finally {sqlSession.close();}}
- 查询的时候,如果某些条件没带,sql的拼装可能出现问题
解决方法,使用where
where
- 第一种方法
给where后面加上1=1,以后的条件都and xxx
- 第二种方法
mybatis使用where标签来将所有的查询条件包括在内。mybatis就会将where标签中拼接的sql,多出来的and或者or去掉,where只会去掉第一个多出来的and或者or。
<!-- public List<Employee> getEmpsByConditionIf(Employee employee);-->
<select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">select * from tb1_employee<where><if test = "id!=null">id = #{id}</if><if test = "lastName!=null && lastName!=""">and last_name like #{lastName}</if><if test="email!=null and email.trim()!=""">and email = #{email}</if><!--ognl会进行字符串与数字的转换判断 "0"==0 --><if test="gender==0 or gender==1">and gender = #{gender}</if></where></select>
trim
后面多出的and或者or where标签不能解决
- prefix = “”:前缀;trim标签体中整个字符串拼串后的结果。
- prefix给拼串后的整个字符串加一个前缀
- prefixOverrides = “”:前缀覆盖;去掉整个字符串多余的字符
- suffix = “”:给拼串后的整个字符串加一个后缀
- suffixOverrides = “”:后缀覆盖;去掉整个字符串后面多余的字符
<!-- public List<Employee> getEmpsByConditionIf(Employee employee);-->
<select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee">select * from tb1_employee<trim prefix="where" suffixOverrides="and"><if test = "id!=null">id = #{id} and</if><if test = "lastName!=null && lastName!=""">last_name like #{lastName} and</if><if test="email!=null and email.trim()!=""">email = #{email} and</if><!--ognl会进行字符串与数字的转换判断 "0"==0 --><if test="gender==0 or gender==1">gender = #{gender}</if></trim></select>