1 在接口中书写方法
public interface EmployeeMapperDynamicSQL {
public List<Employee> getEmpsTestInnerParameter(Employee employee);}
2在映射中进行配置
<!-- 查询员工,要求,携带了哪个字段查询条件就带上这个字段的值 -->
<!-- public List<Employee> getEmpsByConditionIf(Employee employee); --> <select id="getEmpsByConditionIf" resultType="com.atguigu.mybatis.bean.Employee"> select * from tbl_employee <!-- where --> <where> <!-- test:判断表达式(OGNL) OGNL参照PPT或者官方文档。 c:if test 从参数中取值进行判断 遇见特殊符号应该去写转义字符: &&: --> <if test="id!=null"> id=#{id} </if><!-- &为& "为“ --> <if test="lastName!=null && lastName!="""> and last_name like #{lastName} </if> <if test="email!=null and email.trim()!="""> and email=#{email} </if> <!-- ognl会进行字符串与数字的转换判断 "0"==0 --> <if test="gender==0 or gender==1"> and gender=#{gender} </if> </where> </select>3进行测试
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); return new SqlSessionFactoryBuilder().build(inputStream); }@Test
public void testDynamicSql() throws IOException{ SqlSessionFactory sqlSessionFactory = getSqlSessionFactory(); SqlSession openSession = sqlSessionFactory.openSession(); try{ EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class); //select * from tbl_employee where id=? and last_name like ? //测试if\where Employee employee = new Employee(null, "jerry2", null, null); List<Employee> emps = mapper.getEmpsByConditionIf(employee ); for (Employee emp : emps) { System.out.println(emp); } }finally{ openSession.close(); } }