以下知识来源说明:http://www.java1234.com/
mapping
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.java1234.mappers.StudentMapper">
<resultMap type="Student" id="StudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
</resultMap>
<select id="searchStudents" parameterType="Map" resultMap="StudentResult">
select * from t_student
where gradeId=#{gradeId}
<if test="name!=null">
and name like #{name}
</if>
<if test="age!=nulll">
and age=#{age}
</if>
</select>
<select id="searchStudents2" parameterType="Map" resultMap="StudentResult">
select * from t_student
<choose>
<when test="searchBy=='gradeId'">
where gradeId=#{gradeId}
</when>
<when test="searchBy=='name'">
where name like #{name}
</when>
<otherwise>
where age=#{age}
</otherwise>
</choose>
</select>
</mapper>
调用测试
@Test
public void testSearchStudents() {
logger.info("添加学生(带条件)");
Map<String,Object> map=new HashMap<String,Object>();
map.put("gradeId", 2);
// map.put("name", "%李%");
// map.put("age", 11);
List<Student> studentList=studentMapper.searchStudents(map);
for(Student student:studentList){
System.out.println(student);
}
}
@Test
public void testSearchStudents2() {
logger.info("添加学生(带条件)");
Map<String,Object> map=new HashMap<String,Object>();
map.put("searchBy", "age");
map.put("gradeId", 2);
map.put("name", "%李%");
map.put("age", 11);
List<Student> studentList=studentMapper.searchStudents2(map);
for(Student student:studentList){
System.out.println(student);
}
}