四、参数类型Map和模糊查询
一、参数类型Map
1. UserMapper接口
public User getById2(Map map);
public Integer updateById2(Map map);
2. UserMapper.xml
<!--map作为参数-->
<select id="getById2" parameterType="Map" resultType="User">
select * from `user` where id = #{id};
</select>
<!--map作为参数-->
<update id="updateById2" parameterType="Map">
update `user` set name=#{name},pwd=#{pwd} where id = #{id};
</update>
3. 测试类
//map作为参数
@Test
public void getById2(){
SqlSession sqlSession = MyBaitsUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("id",1);
User user = userMapper.getById2(map);
System.out.println(user);
sqlSession.close();
}
@Test
public void updateById2(){
SqlSession sqlSession = MyBaitsUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("id",1);
map.put("name","z6");
map.put("pwd","qweasd");
Integer row = userMapper.updateById2(map);
if (row > 0) {
System.out.println("修改成功");
}
//必须提交事务
sqlSession.commit();
sqlSession.close();
}
二、模糊查询
方式1:
map.put("name","%张%");
List<User> userList= userMapper.getByName(map);
<select id="getByName" parameterType="Map" resultType="User">
select * from `user` where name like #{name};
</select>
方式2:
map.put("name","张");
List<User> userList= userMapper.getByName(map);
<select id="getByName" parameterType="Map" resultType="User">
select * from `user` where name like "%"#{name}"%";
</select>