Mybatis 进行增删查改的时候,如果进行多个参数传递的时候,可以使用到Map,以下进行两个方法的比较:
UserMapper接口UserMapper.java中:
//根据id查询用户
User getUserById(int id);
//map 可定制化Map传递参数直接在SQL中取出Key即可,不用id,name那些一一对应,多个参数传递用map
User getUserById2(Map<String,Object> map);
//insert一个用户
Integer addUser(User user);
//用Map插入
int addUser2(Map<String,Object> map);
UserMapper.xml中:
<!-- 通过指定ID查询用户信息-->
<select id="getUserById" parameterType="int" resultType="com.yang.pojo.User">
select * from mybatis.user where id=#{id}
</select>
<!--map 通过指定ID和名字查询用户信息-->
<select id="getUserById2" parameterType="map" resultType="com.yang.pojo.User">
select * from mybatis.user where id=#{id} and name=#{name}
</select>
<!-- 插入用户数据-->
<insert id="addUser" parameterType="com.yang.pojo.User">
insert into mybatis.user(id,name,password) values(#{id},#{name},#{password})
</insert>
<!--传递Map的Key-->
<insert id="addUser2" parameterType="map">
insert into mybatis.user(id,name,password) values(#{userId},#{userName},#{userPassword})
</insert>
在测试UserDaoTest.java中
查询用户信息:
//根据ID查询用户信息
@Test
public void getUserById(){
SqlSession sqlSession=MybaisUtils.getSqlSession();
UserMapper mapper= sqlSession.getMapper(UserMapper.class);
User user=mapper.getUserById(2);
System.out.println(user);
sqlSession.close();
}
//通过map,根据ID和name查询用户信息
@Test
public void getUserById2(){
SqlSession sqlSession=MybaisUtils.getSqlSession();
UserMapper mapper= sqlSession.getMapper(UserMapper.class);
Map<String,Object> map=new HashMap<String,Object>();
map.put("id",3);
map.put("name","你好");
User user=mapper.getUserById2(map);
System.out.println(user);
sqlSession.close();
}
插入用户信息:
增删改要提交事务,不然会提交不了
sqlSession.commit();
//添加用户
@Test
public void addUser(){
SqlSession sqlSession=MybaisUtils.getSqlSession();
UserMapper mapper= sqlSession.getMapper(UserMapper.class);
Integer isSuccess=mapper.addUser(new User(6,"哈哈","123456"));
if(isSuccess>0) System.out.println("成功");
sqlSession.commit();
sqlSession.close();
}
//map传用户,实际使用中也实用
@Test
public void addUser2(){
SqlSession sqlSession=MybaisUtils.getSqlSession();
UserMapper mapper= sqlSession.getMapper(UserMapper.class);
Map<String,Object> map=new HashMap<String,Object>();
map.put("userId",9);
map.put("userName","花花");
map.put("userPassword","666");
int isSuccess=mapper.addUser2(map);
if(isSuccess>0) System.out.println("成功");
sqlSession.commit();
sqlSession.close();
}