mybatis动态标签——where、if
mapper接口
public interface EmpMapper { List<Emp> getEmp(Emp emp); }
mapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.xxx.dynamicSQL.mapper.EmpMapper"> <!-- if标签:通过test属性中的表达式判断标签中的内容是否有效(是否会拼接到sql中) where标签:1.若where标签中有条件成立,会自动生成where关键字 2.会自动将where标签中内容前多余的and去掉,但是其中内容后多余的and无法去掉 3.若where标签中没有任何一个条件成立,则where也不会自动生成 --> <select id="getEmp" resultType="emp"> select * from t_emp <where> <if test="empName != null and empName != ''"> and emp_name = #{empName} </if> <if test="age != null and age != ''"> and age = #{age} </if> <if test="gender != null and gender != ''"> and gender = #{gender} </if> </where> </select> </mapper>
测试代码
@Test public void test1(){ SqlSession sqlSession = SqlSessionUtil.getSqlSession(); EmpMapper mapper = sqlSession.getMapper(EmpMapper.class); Emp emp = new Emp(null,"李四",null,"男"); List<Emp> list = mapper.getEmp(emp); list.forEach(System.out::println); }