天天看點

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();
    }