Mybatis(万能map)

mybatis(万能map)

我们使用对象作为参数有一个缺点:

  • 我们要在mapper.xml文件和测试中要把所有的字段都写出来,那么,假如一个对象有100个字段,那我们要把这些字段都写出来吗?

所以这时我们就要用到map作为参数

实例:

对象 VS map

接口

int addUser(User user);
int addUser2(Map<String,Object> map);

mapper.xml

<insert id="addUser" parameterType="com.kuang.pojo.User">
    insert into mybatis.user (id,name,pwd) values (#{id},#{name },#{pwd});
</insert>
<insert id="addUser2" parameterType="map">
    insert into mybatis.user(id,name,pwd)values (#{helloid},#{helloname},#{hellopwd});
</insert>

测试

@Test
public void addUser(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    userMapper.addUser(new User(4,"赵六","4664785"));
    sqlSession.commit();
    sqlSession.close();
}
@Test
public void addUser2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String, Object> map = new HashMap<>();
    map.put("helloid",8);
    map.put("helloname","田七");
    map.put("hellopwd","5465555");
    userMapper.addUser2(map);
    sqlSession.close();
}

如果对象中字段非常多的话,我们写起来就很麻烦,所以一定要使用map

总结:

  • 参数为一个时,我们使用基本类型作为参数
  • 参数为多个时,我们使用map作为参数

我今天运行这个测试,怎么都成功不了,一直报错,代码还是没有一点问题,经过一番折腾,发现是因为我在的xml文件的注释中含有中文,万万没有想到这里都会出错

解决方法:将UTF-8改为UTF8

posted on   汪汪程序员  阅读(573)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示