写sql时传入map与模糊查询

  1. 用map进行传参更加灵活,可以随意封装

    举例:

    //接口中的方法
    User selectByMap(Map<String,Object> map);
    

    mapper.xml中的sql语句的编写

    <!--通过map进行条件查询-->
    <select id="selectByMap" resultType="com.test.pojo.User">
        select * from User where id = #{id} and name = #{name}
    </select>
    

    测试代码编写

    //...前面有创建sqlSessionFactory对象和SQLSession对象的代码
    
    Map<String,Object> map = new HashMap<>();
    map.put("id",1);
    map.put("name","zahngsan");
    
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User user = mapper.selectByMap(map);
    System.out.println(user);
    
  2. 模糊查询

    方式一:手动添加“%”通配符

    <!--模糊查询-->
    <select id="selectByName" resultType="com.test.pojo.User">
        select * from mybatis.user where name like #{value};
    </select>
    

    编写测试代码:

    @Test
    public void testSelect(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.selectByName("%李%");
        for (User user : users) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    

    方式二:在xml配置文件中添加"%"通配符,拼接字符串形式

    <!--模糊查询-->
    <select id="selectByName" resultType="com.test.pojo.User">
        select * from mybatis.user where name like '%${value}%';
    </select>
    

    *说明:在mapper.xml配置文件中添加"%"通配符,但是需要用单引号将其包裹住,但是用单引号裹住之后#{}就无法被识别,要改成${}这种拼接字符串的形式。虽然方式二更急简单但同时也造成了SQL安全性的问题,也就是用户可以进行SQL注入。

    方式三:在xml配置文件中添加"%"通配符,借助mysql函数

    <!--模糊查询-->
    <select id="selectByName" resultType="com.test.pojo.User">
        select * from mybatis.user where name like 
        concat('%',#{value},'%');
    </select>
    

    *说明:解决了SQL注入且能在配置文件中写"%"通配符的问题,完美实现了模糊查询

    方式四:使用是${}形式,需要用单引号包裹住

    <!--模糊查询-->
    <select id="selectByName" resultType="com.test.pojo.User">
        select * from mybatis.user where name like 
        concat('%','${value}','%');
    </select>
    

    注意:

    • '#{}'是预编译处理,mybatis在处理#{}时,会将其替换成"?",再调用PreparedStatement的set方法来赋值。
    • ${}是拼接字符串,将接收到的参数的内容不加任何修饰的拼接在SQL语句中,会引发SQL注入问题。
posted @ 2024-05-10 16:10  Hanyta  阅读(8)  评论(0编辑  收藏  举报