首页 /  技术专区  /  Mybatis 宽屏模式 >

Mybatis用Map传值和模糊查询

1、万能的Map传值

假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map!

map灵活度高,可以用自己定义的key,不过相对项目来说不是很规范,看情况使用。


Map传递参数,直接在sq|中取出key即可! [parameterType="map"]

对象传递参数,直接在sq|中取对象的属性即可! [parameterType="Object"]

只有一个基本类型参数的情况下,可以直接在sq|中取到! .

多个参数用Map,或者注解!


map写法例子:

//万能的map
int addUser2(Map<String, Object> map);
<insert id = "addUser2" parameterType = "java.util.HashMap">
    insert into mybatis.user(`id`, `pwd`) values (#{userId}, #{password});
</insert>
@Test
public void addUserMap(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao userDao = sqlSession.getMapper(UserDao.class);

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("userId", 6);
    map.put("password", "test123456");
    int allen = userDao.addUser2(map);
    if(allen > 0){
        System.out.println("新增成功");
        sqlSession.commit();
    }
    sqlSession.close();
}


2、模糊查询怎么写?

1. Java代码执行的时候,传递通配符%%

List<User> userList = userDao.getUserLike("%李%");

2.在sq|拼接中使用通配符!

<select id = "getUserLike" resultType = "com.allen.pojo.User" parameterType = "java.lang.String">
    select * from mybatis.user where `name` like "%"#{name}"%";
</select>




头像
0/200
图片验证码