场景:当我们的实体类,或者数据库中的表,字段或者参数过多,我们可以考虑使用万能Map!!!
- Map 传递参数,直接在 sql 中取出key即可!【parameterType=“map”】
- 对象传递参数,直接在 sql 中取对象的属性即可!【parameterType=“Object”】
- 只有一个基本类型参数的情况下,可以直接在 sql 中取到!
- 多个参数用Map,或者注解!
public class User {
private Integer id;
private String name;
private String pwd;
public User() {
}
public User(Integer id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
int addUser(Map<String, Object> map);
<insert id="addUser" parameterType="map">
insert into `user` (id,pwd) values (#{userId},#{passWord})
</insert>
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("userId",5);
map.put("passWord","456123");
mapper.addUser(map);
sqlSession.commit();
sqlSession.close();
}