学习目标:

MyBatis中Map的使用


学习内容:

MyBatis中Map的使用


学习时间:


学习产出:

Map的使用

注意:当实体类或数据库中的表,字段或者参数过多时,应该使用map

Map添加内容

XML

<!--Map的使用-->
    <insert id="addUser2" parameterType="map">
        insert into user (id,name,pwd) values (#{userid},#{username},#{userpwd});
    </insert>

Mapper接口

    //Map的使用
    int addUser2(Map<String,Object> map);

Test

//Map测试
    @Test
    public void addUser2() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userid",5);
        map.put("username","牛七");
        map.put("userpwd","12345");
        int result = mapper.addUser2(map);
        if (result > 0) {
            System.out.println("添加成功!");
        }
        //增删改一定要提交事务!
        sqlSession.commit();
        sqlSession.close();
    }

Map查询内容

XML

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

Mapper接口

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

Test

@Test
    public void getUserList2() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userid", 6);
        map.put("username", "牛八");
        User user = mapper.getUserById2(map);
        System.out.println(user);
        //增删改一定要提交事务!
        sqlSession.commit();
        sqlSession.close();
    }

xml中parameterType="map"的map代表的是传入的整个map,只要sql语句中
取出的key在传入的map中有就可以用(这代表sql可以进行多个字段绑定的查询,只要在传入的map中有)

总结

  • Map传递参数,直接在sql中取出key即可
  • 对象传递参数,直接在sql中取出对象即可
  • 只有一个基本类型参数的情况下,可以直接在sql中取到
  • 多个参数用Map或者注解

更多推荐

MyBatis使用Map