转自:wangchuanfu 的 《mybatis之parameterType传递多个参数》
原址:https://www.cnblogs.com/wangchuanfu/p/5877169.html
当在查询的时候需要传入多个参数的时候该怎么办呢:
1,封装成一个Model对象,底层HashMap还是一个
User user=new User();
user.setUserName("zhangsan");
user.setPassword("123456");
queryUserByuserNameAndPass(user);//为返回值类型为User
2,使用HashMap封装
//使用HashMap定义:
HashMap map=new HashMap();
map.put("userName","zhangsan");
map.put("password","123456");
queryUserByuserNameAndPass(map);//为返回值类型为User
//sql 如下:
3,使用注解,@param
queryUserByuserNameAndPass(@param(''userName")String userName,@param("password")String password)
queryUserByuserNameAndPass(String userName,String PassWord); //返回值类型为Usre
//sql
改为如下:
//parameterType 参数类型可以是基本数据类型(int,String,long),可以是Model对象,也可以是Map;
1,基本数据类型:
@Override
public void deleteUserById(Long id) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
sqlSession.delete("cn.itcast.mybatis.user.deleteUserById", id);
}
//sql
DELETE FROM tb_user WHERE id = #{id}
2,Model对象
@Override
public void saveUser(User user) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
sqlSession.insert("cn.itcast.mybatis.user.saveUser", user);
}
@Override
public void updateUser(User user) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
sqlSession.update("cn.itcast.mybatis.user.updateUser", user);
}
//sql
UPDATE tb_user
SET
password = #{password},
name = #{name},
age = #{age},
sex = #{sex},
birthday = #{birthday},
updated = NOW()
WHERE
id = #{id};
3.map
HashMap map=new HashMap();
map.put("userName","zhangsan");
map.put("password","123456");
queryUserByuserNameAndPass(map);//为返回值类型为User
//sql 如下: