使用Choose构建分支动态语句

1.在接口写方法

public List<Employee> getEmpsByConditionChoose(Employee employee);

2 在映射文件中配置

<!-- public List<Employee> getEmpsByConditionChoose(Employee employee); -->
<select id="getEmpsByConditionChoose" resultType="com.atguigu.mybatis.bean.Employee">
select * from tbl_employee
<where>
<!-- 如果带了id就用id查,如果带了lastName就用lastName查;只会进入其中一个 ,如果都没有就默认查询条件为gender=0-->
<choose>
<when test="id!=null">
id=#{id}
</when>
<when test="lastName!=null">
last_name like #{lastName}
</when>
<when test="email!=null">
email = #{email}
</when>
<otherwise>
gender = 0
</otherwise>
</choose>
</where>
</select>

3进行测试

@Test
public void testDynamicSql() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
Employee employee = new Employee(null, null, null, null);
Employee employee1= new Employee(null, "jerry2", null, null);
//测试choose
List<Employee> list = mapper.getEmpsByConditionChoose(employee);
for (Employee emp : list) {
System.out.println(emp);
}
List<Employee> list2 = mapper.getEmpsByConditionChoose(employee1);
for (Employee emp : list2) {
System.out.println(emp);
}

}finally{
openSession.close();
}
}

4运行结果

原文地址:https://www.cnblogs.com/zhangzhiqin/p/8565735.html