zoukankan      html  css  js  c++  java
  • 3、使用Map传参 & 模糊查询

    1、 Map传参的使用

    当我们的实体类或者数据库中的表,字段或者参数过多时,我们应当考虑使用Map!(优点:可以不用插入指定的参数,比较灵活)

    mapper中添加如下方法:

    //使用Map传参添加用户
    int addUser2(Map<String,Object> map);
    //使用Map传参修改用户信息
    int updateUser2(Map<String,Object> map);
    

    编写mapper映射:

    <insert id="addUser2" parameterType="map">
        insert into mybatis.user (name, pwd) values(#{userName},#{passWorld}) ;
    </insert>
    
    <update id="updateUser2" parameterType="map">
        update mybatis.user set name=#{userName},pwd=#{password} where id=#{userId} ;
    </update>
    

    编写测试:

    @Test
    public void testGeneralMap(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("userName","钻石王老五");
        map.put("passWorld","23333");
        System.out.println(mapper.addUser2(map) > 0 ? "添加成功" : "添加失败");
        // 增删改需要提交事务
        sqlSession.commit();
        // 关闭SqlSession
        sqlSession.close();
    }
    @Test
    public void testGeneralMap2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("userId",4);
        map.put("userName","小花");
        map.put("password","123");
        System.out.println(mapper.updateUser2(map) > 0 ? "修改成功" : "修改失败");
        // 提交事务
        sqlSession.commit();
        sqlSession.close();
    }
    

    最终表数据如下:

    image

    2、模糊查询

    (1) 在Java代码执行的时候,传递通配符 % 内容 %

    image


    (2) 在SQL拼接中使用通配符。

    image

  • 相关阅读:
    如何很好的使用Linq的Distinct方法
    根据字符串获取对应类型(Type) 转
    .Net 读取xml
    认识ASP.NET MVC的5种AuthorizationFilter
    使用admin插入数据失败
    乱序批量精确修改文件名
    多进程+协程方案处理高IO密集,提升爬取效率
    Linux 安装 CMake
    Ubuntu 截图工具deepin-screenshot添加使用
    Linux virtualenv .bashrc配置文件
  • 原文地址:https://www.cnblogs.com/m987/p/15339963.html
Copyright © 2011-2022 走看看