mybatis动态sql-(3)-单次条件判断choose

单次判断,就是只进行一次判断。

一、编辑接口文件

import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.mybatis.bean.Employee;

public interface EmployeeMapperDynamicSQL {

       public List<Employee> getEmpsByConditionChoose(Employee employee);

}

二、编辑SQL映射文件

 <!-- public List<Employee> getEmpsByConditionChoose(Employee employee); -->
 <select id="getEmpsByConditionChoose" resultType="com.mybatis.bean.Employee">
	 select * from tbl_employee 
	 <where>
	 	<!-- 如果带了id就用id查,如果带了lastName就用lastName查;只会进入其中一个 -->
	 	<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>

三、Junit单元测试

EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
Employee employee = new Employee(3,"%m%","[email protected]","2");

List<Employee> list = mapper.getEmpsByConditionChoose(employee);
	for(Employee emp :list){
	System.out.println(emp);
	System.out.println(emp.getDepartment());
}

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments