天天看点

MyBatis 用Map作为参数,模糊查询

MyBatis

Parameter用Map替代对象

dao:

xml

<select id="getUserById2" parameterType="map" resultType="com.vv.pojo.User">
        select * from mybatis.user where id= #{helloid} and name = #{name}
    </select>
           

test

public void getUserById2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("helloid",21);
        map.put("name","Alex");
        System.out.println(mapper.getUserById2(map));

        sqlSession.close();
    }
           

Map传递参数,直接在sql中取出对应的key

对象传递参数直接在sql中取出对象的属性

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

多个参数用Map,或者注解@Param

模糊查询

dao

xml

<select id="getUserLike" resultType="com.vv.pojo.User">
        select * from mybatis.user where name like '%${name}%'
    </select>
           

test

public void getUserLike(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.getUserLike("v");

        for(User user : userList){
            System.out.println(user);
        }
        sqlSession.close();
    }