Skip to content

Commit 6f20b1d

Browse files
author
zhangkai
committed
fix: Dao接口中方法重载的补充
1 parent 639a9a7 commit 6f20b1d

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

docs/system-design/framework/mybatis/mybatis-interview.md

+75
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,81 @@ public interface StuMapper {
6868

6969
Dao 接口的工作原理是 JDK 动态代理,MyBatis 运行时会使用 JDK 动态代理为 Dao 接口生成代理 proxy 对象,代理对象 proxy 会拦截接口方法,转而执行`MappedStatement`所代表的 sql,然后将 sql 执行结果返回。
7070

71+
##### ==补充:==
72+
73+
Dao接口方法可以重载,但是需要满足以下条件:
74+
75+
1. 仅有一个无参方法和一个有参方法
76+
2. 多个有参方法时,参数数量必须一致。且使用相同的 `@Param` ,或者使用 `param1` 这种
77+
78+
测试如下:
79+
80+
`PersonDao.java`
81+
82+
```java
83+
Person queryById();
84+
85+
Person queryById(@Param("id") Long id);
86+
87+
Person queryById(@Param("id") Long id, @Param("name") String name);
88+
```
89+
90+
`PersonMapper.xml`
91+
92+
```xml
93+
<select id="queryById" resultMap="PersonMap">
94+
select
95+
id, name, age, address
96+
from person
97+
<where>
98+
<if test="id != null">
99+
id = #{id}
100+
</if>
101+
<if test="name != null and name != ''">
102+
name = #{name}
103+
</if>
104+
</where>
105+
limit 1
106+
</select>
107+
```
108+
109+
`org.apache.ibatis.scripting.xmltags.DynamicContext.ContextAccessor#getProperty`方法用于获取`<if>`标签中的条件值
110+
111+
```java
112+
public Object getProperty(Map context, Object target, Object name) {
113+
Map map = (Map) target;
114+
115+
Object result = map.get(name);
116+
if (map.containsKey(name) || result != null) {
117+
return result;
118+
}
119+
120+
Object parameterObject = map.get(PARAMETER_OBJECT_KEY);
121+
if (parameterObject instanceof Map) {
122+
return ((Map)parameterObject).get(name);
123+
}
124+
125+
return null;
126+
}
127+
```
128+
129+
`parameterObject`为map,存放的是Dao接口中参数相关信息。
130+
131+
`((Map)parameterObject).get(name)`方法如下
132+
133+
```java
134+
public V get(Object key) {
135+
if (!super.containsKey(key)) {
136+
throw new BindingException("Parameter '" + key + "' not found. Available parameters are " + keySet());
137+
}
138+
return super.get(key);
139+
}
140+
```
141+
142+
1. `queryById()`方法执行时,`parameterObject`为null,`getProperty`方法返回null值,`<if>`标签获取的所有条件值都为null,所有条件不成立,动态sql可以正常执行。
143+
2. `queryById(1L)`方法执行时,`parameterObject`为map,包含了`id``param1`两个key值。当获取`<if>`标签中`name`的属性值时,进入`((Map)parameterObject).get(name)`方法中,map中key不包含`name`,所以抛出异常。
144+
3. `queryById(1L,"1")`方法执行时,`parameterObject`中包含`id`,`param1`,`name`,`param2`四个key值,`id``name`属性都可以获取到,动态sql正常执行。
145+
71146
#### 4、MyBatis 是如何进行分页的?分页插件的原理是什么?
72147

73148
注:我出的。

0 commit comments

Comments
 (0)