3.2 动态SQL
接口方法
/**
* - 当 studen_id 有值时, 使用 studen_id 进行查询;
* - 当 studen_id 没有值时, 使用 name 进行查询;
* - 否则返回空
*/
Student selectByIdOrName(Student record);
对应的SQL
< selectid= "selectByIdOrName"resultMap= "BaseResultMap"parameterType= "com.homejim.mybatis.entity.Student">
select
fromstudent
where1= 1
< whentest= "studentId != null">
andstudent_id= #{studentId}
when>
< whentest= "name != null and name != ''">
andname= #{name}
when>
and1= 2
select>
3.3 测试
@ Test
publicvoidselectByIdOrName() {
SqlSession sqlSession = null;
sqlSession = sqlSessionFactory.openSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = newStudent();
student.setName( "小飞机");
student.setStudentId( 1);
Student studentById = studentMapper.selectByIdOrName(student);
System. out.println( "有 ID 则根据 ID 获取");
System. out.println(ToStringBuilder.reflectionToString(studentById, ToStringStyle.MULTI_LINE_STYLE));
student.setStudentId( null);
Student studentByName = studentMapper.selectByIdOrName(student);
System. out.println( "没有 ID 则根据 name 获取");
System. out.println(ToStringBuilder.reflectionToString(studentByName, ToStringStyle.MULTI_LINE_STYLE));
student.setName( null);
Student studentNull = studentMapper.selectByIdOrName(student);
System. out.println( "没有 ID 和 name, 返回 null");
Assert.assertNull(studentNull);
sqlSession.commit();
sqlSession.close();
}
有 ID 则根据 ID 获取, 结果
没有 ID 则根据 name 获取
没有 ID 和 name, 返回 null