当前位置:  首页>> 技术小册>> Mybatis合辑3-Mybatis动态SQL

  • 示例:
  • EmployeeMapper.java
  1. package com.sunxiaping.mapper;
  2. import com.sunxiaping.domain.Employee;
  3. import java.util.List;
  4. public interface EmployeeMapper {
  5. List<Employee> getEmpsByConditionIf(Employee employee);
  6. }
  • EmployeeMapper.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.sunxiaping.mapper.EmployeeMapper">
  6. <select id="getEmpsByConditionIf" resultType="com.sunxiaping.domain.Employee">
  7. SELECT id as id,last_name as lastName,gender as gender,email as email
  8. FROM employee
  9. WHERE 1 = 1
  10. <!--
  11. test:条件判断表达式OGNL
  12. -->
  13. <if test="id != null">
  14. AND id = #{id,jdbcType=INTEGER}
  15. </if>
  16. <if test="lastName != null and lastName != ''">
  17. AND last_name LIKE #{lastName,jdbcType=VARCHAR}
  18. </if>
  19. <if test="gender != null and gender != ''">
  20. AND gender = #{gender,jdbcType=VARCHAR}
  21. </if>
  22. <if test="email != null and email != ''">
  23. AND email = #{email,jdbcType=VARCHAR}
  24. </if>
  25. </select>
  26. </mapper>
  • 测试:
  1. package com.sunxiaping;
  2. import com.sunxiaping.domain.Employee;
  3. import com.sunxiaping.mapper.EmployeeMapper;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import org.junit.After;
  9. import org.junit.Before;
  10. import org.junit.Test;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.util.List;
  14. public class EmployeeTest {
  15. SqlSessionFactory sqlSessionFactory = null;
  16. SqlSession sqlSession = null;
  17. EmployeeMapper employeeMapper = null;
  18. @Before
  19. public void before() throws IOException {
  20. String resource = "mybatis-config.xml";
  21. InputStream inputStream = Resources.getResourceAsStream(resource);
  22. sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  23. sqlSession = sqlSessionFactory.openSession(true);
  24. employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
  25. }
  26. @After
  27. public void after() {
  28. if (null != sqlSession) {
  29. sqlSession.close();
  30. }
  31. }
  32. @Test
  33. public void testFindById() {
  34. Employee example = new Employee();
  35. example.setId(1);
  36. example.setGender("男");
  37. List<Employee> employeeList = employeeMapper.getEmpsByConditionIf(example);
  38. System.out.println("employeeList = " + employeeList);
  39. }
  40. }

该分类下的相关小册推荐: