mybatis:where标签(特殊的trim标签使用?)

以下知识来源说明:http://www.java1234.com/

where标签:

1、自动加上where

2、如果where子句以and或者or开头,则自动删除第一个and或or

trim标签:

功能和 where 元素类似,提供了前缀,后缀功能,更加灵活;

StudentMapper.xml

<select id="searchStudents3" parameterType="Map" resultMap="StudentResult">
    select * from t_student 
     <where>
         <if test="gradeId!=null">
            gradeId=#{gradeId}
         </if>
         <if test="name!=null">
            and name like #{name}
         </if>
         <if test="age!=nulll">
            and age=#{age}
         </if>
     </where>
</select>

<select id="searchStudents4" parameterType="Map" resultMap="StudentResult">
    select * from t_student 
     <trim prefix="where" prefixOverrides="and|or">
         <if test="gradeId!=null">
            gradeId=#{gradeId}
         </if>
         <if test="name!=null">
            and name like #{name}
         </if>
         <if test="age!=nulll">
            and age=#{age}
         </if>
     </trim>
</select>

junit测试

@Test
public void testSearchStudents3() {
    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.searchStudents3(map);
    for(Student student:studentList){
        System.out.println(student);
    }
}

@Test
public void testSearchStudents4() {
    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.searchStudents4(map);
    for(Student student:studentList){
        System.out.println(student);
    }
}

猜你喜欢

转载自blog.csdn.net/m0_38084243/article/details/82380152