1 背景
当SQL语句中仅需要某些字段时,不必要将整个对象作为参数传入,因为实际项目中对象的属性可能很多,而SQL语句中不一定要用到这么多字段
2 应用
2.1 mapper接口
mapper接口定义如下:
//用map
int addUser2(Map<String, Object> map);
2.2 mapper.xml
注意parameterType为小写的map即可,values字段对应为map对应的key
<!--新增用户,用map-->
<insert id="addUser2" parameterType="map">
insert into user (id, name, pwd)
values (#{userId}, #{userName}, #{password})
</insert>
2.3 测试
// 新增用户用map
@Test
public void addUser2Test() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map map = new HashMap<String, Object>();
map.put("userId", 4);
map.put("userName", "hello");
map.put("password", "222333");
int res = mapper.addUser2(map);
System.out.println("影响行数:" + res);
//提交事务
sqlSession.commit();
sqlSession.close();
}