万能的Map

假设,我们的实体类或数据库中的表,字段或参数过多,我们应当考虑使用Map

添加:

   //insert一个用户   切记不可方法重组
   int addUser2(Map<String,Object> map);
    <insert id="addUser2" parameterType="map">
insert into mybatis.user (id,pwd) value (#{userid},#{userpwd})
    </insert>

 

 @Test
    public void addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String,Object> map=new HashMap<>();
        map.put("userid",5);
        map.put("userpwd","lala");
        mapper.addUser2(map);
        sqlSession.commit();
        sqlSession.close();
    }

查找:

 User getUserById2(Map<String,Object> map);

 

  
@Test
    public void getUserById2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String,Object> map=new HashMap<>();
        map.put("yourid",2);
        map.put("name","张三");
        User userById = mapper.getUserById2(map);
        System.out.println(userById);
        sqlSession.commit();
        sqlSession.close();
    }

 

<select id="getUserById2" parameterType="map" resultType="com.kuang.pojo.User">
     select * from mybatis.user where id=#{yourid} and name=#{name}
 </select>

 

  • map传递参数,直接在sql中取出key即可

  • 对象传递参数,直接在sql中取出对象的属性即可

  • 只有一个基本类型参数的情况下,可以直接在sql中取到

另外模糊查询Java代码执行的时候,传递通配符

<select id="getUserListlike" resultType="com.kuang.pojo.User">    select * from mybatis.user where name like #{value}</select>
 List<User> userList = mapper.getUserListlike("%李%");
<select id="getUserListlike" resultType="com.kuang.pojo.User">    select * from mybatis.user where name like "%"#{value}"%"</select>
 

 

posted @ 2020-04-16 11:09  我是小杨  阅读(223)  评论(0)    收藏  举报