当前位置:主页 > 软件编程 > JAVA代码 >

MyBatis中map的应用与模糊查询实现代码

时间:2023-01-23 08:25:10 | 栏目:JAVA代码 | 点击:

1.MyBatis中map的应用

1.1.应用场景

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

1.2.具体实现

//万能map
int addUser2(Map<String,Object> map);
    <!--对象中的属性,可以直接取出来 parameterType=传递map中的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.注意点!!!

2.模糊查询

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

    }

您可能感兴趣的文章:

相关文章