mybatis动态sql使用:choose分支选择

时间:2024-10-14 18:40:18

1、我们的业务是如果带了id就用id查,如果带了lastName就用lastName查,只会进入进入一个查询。在DAO中顶一个方法:package com.gwolf.dao;import java.util.Map;import org.apache.ibatis.annotations.MapKey;import com.gwolf.bean.Employee;public interface EmployeeMapper { public List<Employee> getEmpsByConditionChoose(Employee employee); }

mybatis动态sql使用:choose分支选择

2、在xml中定义choose的sql语句定义。<select id="getEmpsByConditionChoose" resultMap="MyEmpByStep" databaseId="mysql"> select * from tbl_emp <where> <choose> <when test="empId!=null"> emp_id = #{empId} </when> <when test="empName!=null"> emp_name = #{empName} </when> </choose> </where>

mybatis动态sql使用:choose分支选择

3、编写junit单元测试方法:@Test public void test1() throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class); Employee employee = new Employee(); employee.setEmpId(1); List<Employee> employees = employeeMapper.getEmpsByConditionChoose(employee); System.out.println(employees); }finally { sqlSession.close(); } }

mybatis动态sql使用:choose分支选择

4、当我们只根据员工id查询的时候,我们的sql只会查询出员工的where子句,运行单元结果,查看控制台sql语句

mybatis动态sql使用:choose分支选择

5、编写根据员工和姓名查询的junit单元测试方法: @Test public void test1() throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); try { EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class); Employee employee = new Employee(); employee.setEmpId(1); employee.setEmpName("曹"); List<Employee> employees = employeeMapper.getEmpsByConditionChoose(employee); System.out.println(employees); }finally { sqlSession.close(); } }

mybatis动态sql使用:choose分支选择

6、当我们查询条件员工id和员工姓名的时候,我们的sql也只会查询出员工的where子句,运行单元测试,查看后台sql语句打印结果。

mybatis动态sql使用:choose分支选择
© 手抄报圈