万能的Map

使用map的原因是因为我们使用实体类时,实体类的参数过多,书写的时候太过于繁琐,因此用map来写能大大减轻书写量

接口文件中的对比:

//增加一个用户
int addUser(User user);

//万能的map
int addUser2(Map<String,Object> map);

xml文件中的对比:

<!--对象中的属性,可以直接取出来-->
<insert id="addUser" parameterType="com.superman.pojo.User">
    insert into mybatis.user(id,username,birthday,sex,address) values (#{id},#{username},#{birthday},#{sex},#{address});
</insert>

<!--使用万能的map,传递map的key-->
<insert id="addUser2" parameterType="map">
    insert into mybatis.user (id,username) values (#{id},#{username})
</insert>

测试中的对比:

@Test
public void addUser() {
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    mapper.addUser(new User(5, "caiji", "20201005", "男", "北京"));

    //提交事务,否则数据库将不会发生变化,即使输出打印时显示插入成功
    sqlSession.commit();
    sqlSession.close();
}

@Test
public void addUser2() {
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("id", 5);
    map.put("username", "caiji");

    mapper.addUser2(map);
    sqlSession.commit();
    sqlSession.close();
}
发布了35 篇原创文章 · 获赞 48 · 访问量 8872

猜你喜欢

转载自blog.csdn.net/weixin_43894771/article/details/104931846