• Mybatis使用map传递参数与模糊查询写法


      前言:你有没有遇到这种情况:当你使用mybatis修改表数据时,你只想改动几个字段,但是你的实体类封装的数据太多了,有上百条数据,

    你若是创建这么一个实体类,那么真的要折腾死人。有没有什么办法只传递几个你想要的数据呢?下面来看看这种使用map传值的方式:

    数据库有这么一个表student且数据只有一条:

    你现在想把这条数据中的sname改为王云云,sgender改为女。

    先在对应的Mapper接口中编写方法updateById():

    public int updateById(Map<String,Object> map);

    在对应的Mapper.xml中绑定参数并编写sql:

    <update id="updateById" parameterType="map">
        update mybatis.student set sname=#{sname},sgender=#{sgender} where id = #{id};
    </update>

    写相应的java代码进行修改的测试:

    @Test
    public void updateById(){
       SqlSession sqlSession = MybatisUtils.getSqlSession();
       UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
       Map<String,Object> map = new HashMap<String,Object>();
       map.put("sname","王云云");
       map.put("sgender","女");
       map.put("sid","1001");
       userMapper.updateById(map);
       sqlSession.commit();
       sqlSession.close();
    }

    运行测试代码并查看结果:

    修改成功!

    mybatis中如何写模糊查询避开sql注入?

    1、java代码执行的时候传递通配符%%:

    mapper.getUser("%王%");

    2、sql拼接时就使用通配符:

    select * from user where name like "%"#{value}"%"
  • 相关阅读:
    SQL 中单引号 和一些特殊字符的处理
    jquery 删除table行,该如何解决
    jQuery获取Select选中的Text和Value,根据Value值动态添加属性等
    C#中DataTable
    jquery操作select(取值,设置选中)
    JS刷新页面总和!多种JS刷新页面代码!
    VS中代码对齐等快捷键
    SQL递归查询(with cte as)
    SQL Server 公用表表达式(CTE)实现递归的方法
    linux ls和 ll 命令
  • 原文地址:https://www.cnblogs.com/wmskywm/p/13582599.html
Copyright © 2020-2023  润新知