---
# System prepended metadata

title: Map和模糊查詢拓展
tags: [Mybatis-基礎]

---

# Map和模糊查詢拓展
###### tags: `Mybatis-基礎`

假設，我們的實體類，或者數據庫中的表、字段或者參數過多，我們應當考慮使用Map！
#### 例子1：add
```java=
    //萬能的Map
    int addUser2(Map<String,Object> map);
```

```xml=
    <!--對象中的屬性，可以直接取出來，傳遞map的key
    -->
    <insert id="addUser2" parameterType="map">
        insert into mybatis.user(id,name,pwd) values (#{userid},#{userName},#{passWord});
    </insert>
```

```java=
    //增刪改需要提交事務
    @Test
    public void addUser2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        Map<String, Object> map = new HashMap<>();

        map.put("userid",5);
        map.put("userName","hello");
        map.put("passWord","222333");

        mapper.addUser2(map);

        //提交事務
        sqlSession.commit();
        sqlSession.close();
    }
```

![](https://i.imgur.com/K4vChNP.png)

使用Map方式，就不用每個參數都輸入，可以自行選擇參數輸入
```java=
        map.put("userid",8);
        map.put("passWord","222333");
```
![](https://i.imgur.com/arb5smr.png)


#### 例子2：查詢
```java=
    //用Map來查詢
    User getUserById2(Map<String,Object> map);
```

```xml=
    <select id="getUserById2" parameterType="map" resultType="com.kuang.pojo.User">
        select * from mybatis.user where id = #{helloId} and name = #{name};
    </select>
```

```java=
    @Test
    public void getUserById2(){
        //獲取執行Sql對象
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        //相當於UserMapper mapper = new UserMapperImpl();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        Map<String, Object> map = new HashMap<>();

        map.put("helloId",2);

        User userById2 = mapper.getUserById2(map);

        System.out.println(userById2);

        sqlSession.close();
    }
```

### 參數傳遞整理
* Map傳遞參數，直接在Sql中取出key即可-->parameterType="map"
* 對象傳遞參數，直接在Sql中取對象屬性即可-->parameterType="Objectt"
* 只有一個基本類型參數的情況下，可以直接在sql中取到-->可以不寫
* 多個參數用Map，**或者註解**

### 模糊查詢怎麼寫？
1. java代碼執行的時候，傳遞通配符%%
```java
List<User> userList = mapper.getUserLike("%李%");
```
2. 在sql拼接中使用通配符
```xml=
select * from mybatis.user where name like "%"#{value}"%"
```

#### 例子
```java=
List<User> getUserLike(String value);
```

```xml=
    <select id="getUserLike" resultType="com.kuang.pojo.User">
<!--在模糊前後用"%"夾住，避免用戶使用其他寫法導致查詢失效       -->
        select * from mybatis.user where name like "%"#{value}"%"
    </select>
```

```java=
    @Test
    public void getUserLike(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = mapper.getUserLike("李");

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

        sqlSession.close();
    }
```

![](https://i.imgur.com/gM9ArGe.png)
