3、使用Map传参 & 模糊查询

1、 Map传参的使用

当我们的实体类或者数据库中的表,字段或者参数过多时,我们应当考虑使用Map!(优点:可以不用插入指定的参数,比较灵活)

mapper中添加如下方法:

//使用Map传参添加用户
int addUser2(Map<String,Object> map);
//使用Map传参修改用户信息
int updateUser2(Map<String,Object> map);

编写mapper映射:

<insert id="addUser2" parameterType="map">
    insert into mybatis.user (name, pwd) values(#{userName},#{passWorld}) ;
</insert>

<update id="updateUser2" parameterType="map">
    update mybatis.user set name=#{userName},pwd=#{password} where id=#{userId} ;
</update>

编写测试:

@Test
public void testGeneralMap(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    Map<String,Object> map = new HashMap<String, Object>();
    map.put("userName","钻石王老五");
    map.put("passWorld","23333");
    System.out.println(mapper.addUser2(map) > 0 ? "添加成功" : "添加失败");
    // 增删改需要提交事务
    sqlSession.commit();
    // 关闭SqlSession
    sqlSession.close();
}
@Test
public void testGeneralMap2(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("userId",4);
    map.put("userName","小花");
    map.put("password","123");
    System.out.println(mapper.updateUser2(map) > 0 ? "修改成功" : "修改失败");
    // 提交事务
    sqlSession.commit();
    sqlSession.close();
}

最终表数据如下:

image

2、模糊查询

(1) 在Java代码执行的时候,传递通配符 % 内容 %

image


(2) 在SQL拼接中使用通配符。

image

原文地址:https://www.cnblogs.com/m987/p/15339963.html