Mybatis中多字段模糊查询

  在做项目的时候遇到要对多个字段进行模糊查询,不同于之前的要求,字段的选择要根据页面的选择来进行增改,这就需要用到动态的sql语句来进行对数据库操作,及时把需要的数据渲染到前端页面。


  在Mybatis中动态sql语句需要借助标签来实现,若前端页面传回的参数包括我们需要的参数,就动态增加一个sql语句。下例:

<select id="queryStudentByinfo" parameterType="map" resultType="com.wxeducation.pojo.Student">
      select * from student where 1=1
          <if test="grade!=null">
              and grade like '%${grade}%'
          </if>

          <if test="teach_type!=null">
              and teach_type like '%${teach_type}%'
          </if>

          <if test="subject!=null">
              and subject like '%${subject}%'
          </if>
</select>

  在上述代码片段中可以看到,我们在常规的sql语句上加了where 和 1=1,where是为了让后序的拼接sql语句可以正常执行,1=1是为了让若没有满足条件的后序拼接sql片段,整条sql语句也能找到数据而不会报错。

  通常,if中的参数用map封装传递:

@PostMapping("/search")
  public List<Student> search(@RequestBody JSONObject req){
      
      String subject = req.getString("subject");
      String grade = req.getString("teach_object");
      String teach_type = req.getString("teach_type");

      HashMap map = new HashMap();
      if(!subject.isEmpty()){
          map.put("subject",subject);
      }
      if(!grade.isEmpty()){
          map.put("grade",grade);
      }
      if(!teach_type.isEmpty()){
          map.put("teach_type",teach_type);
      }

      List<Student> students = studentMapper.queryStudentByinfo(map);
      return students;
  }