美文网首页
mybatis 多条件查询

mybatis 多条件查询

作者: 笨的很想飞 | 来源:发表于2023-03-28 09:15 被阅读0次

    MyBatis 中的多条件查询可以通过不同的方式来实现。下面介绍两种常用的方法。

    1. 使用 Map 传递参数
      第一种方法是使用 Map 来传递查询条件。具体步骤如下:
    
    
    //1.在 Mapper 接口中定义查询方法,方法中的参数为一个 Map,其中 Map 的 key 为查询条件的名称,value 为查询条件的值。例如:
    List<User> selectUsersByConditions(Map<String, Object> params);
    
    //2.在 Mapper XML 文件中编写 SQL 语句,使用 <if> 标签来根据条件动态生成 SQL。例如:
    <select id="selectUsersByConditions" resultType="User">
      select * from user
      <where>
        <if test="name != null and name != ''">
          and name like #{name}
        </if>
        <if test="age != null">
          and age = #{age}
        </if>
        <!-- 其他条件 -->
      </where>
    </select>
    
    
    //3.在调用查询方法时,将查询条件封装成一个 Map,并传入方法中。例如:
    Map<String, Object> params = new HashMap<>();
    params.put("name", "张三");
    params.put("age", 18);
    List<User> users = userMapper.selectUsersByConditions(params);
    
    
    
    1. 使用注解和 @Param 注解
    
    
    //1.在 Mapper 接口中定义查询方法,方法的参数使用 @Param 注解来指定查询条件的名称。例如:
    List<User> selectUsersByConditions(@Param("name") String name, @Param("age") Integer age);
    
    //2.在 Mapper XML 文件中编写 SQL 语句,使用 ${} 占位符引用参数。例如:
    <select id="selectUsersByConditions" resultType="User">
      select * from user
      where name like '%${name}%'
      <if test="age != null">
        and age = #{age}
      </if>
      <!-- 其他条件 -->
    </select>
    
    //3.在调用查询方法时,将查询条件作为方法参数传入。例如:
    List<User> users = userMapper.selectUsersByConditions("张三", 18);
    
    
    //4.需要注意的是,在使用第二种方法时要特别谨慎,因为 ${} 占位符会将参数直接拼接到 SQL 语句中,容易导致 SQL 注入漏洞。
    因此,建议在使用时避免使用这种方法或者对输入的参数做严格的校验和过滤。
    
    
    

    相关文章

      网友评论

          本文标题:mybatis 多条件查询

          本文链接:https://www.haomeiwen.com/subject/ccmtddtx.html