Application of map in MyBatis and Implementation Code of Fuzzy Query

  • 2021-12-11 07:35:09
  • OfStack

Directory 1. MyBatis map Application 1.1. Application Scenario 1.2. Specific implementation 1.3. Attention! ! ! 2. Fuzzy query

1. Application of map in MyBatis

1.1. Application Scenarios

Assuming that there are too many entity classes, or tables, fields, or parameters in the database, you should consider using Map! ! !

1.2. Implementation


// Omnipotent map
int addUser2(Map<String,Object> map);

    <!-- The attributes in the object can be fetched directly  parameterType= Transfer map In key-->
    <insert id="addUser" parameterType="map">
        insert into mybatis.user (id, name, pwd) values (#{userId},#{userName},#{passWord});
    </insert>

    @Test
    public void addUser(){
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("userid",5);
            map.put("userName", "Hello");
            map.put("passWord","123456");
            userMapper.addUser2(map);
            sqlSession.commit();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
    }

1.3. Be careful! ! !

Map passes parameters, and key can be taken out directly in sql! "parameterType=" map "" Object transfer parameters, directly in sql to take the attributes of the object! "parameterType=" Object "" If there is only one basic type parameter, it can be obtained directly in sql! Multiple parameters with Map, or annotations!

2. Fuzzy query


User gteUserById(Map<String,Object> map);

<select id="getUserLike" resultType="com.pojo.User">
    select * from mybatis.user where name like #{value}
    </select>

 @Test
    public void getUserLike(){
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtils.getSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            List<User> userList = userMapper.getUserLike("%lyh%");
            for(User user : userList){
                System.out.println(user);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }

    }

Related articles: