Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit aa9cef3

Browse filesBrowse files
committed
Update mybatis-interview.md
1 parent 8409416 commit aa9cef3
Copy full SHA for aa9cef3

File tree

Expand file treeCollapse file tree

1 file changed

+37
-2
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+37
-2
lines changed
Open diff view settings
Collapse file

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

Copy file name to clipboardExpand all lines: docs/system-design/framework/mybatis/mybatis-interview.md
+37-2Lines changed: 37 additions & 2 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,46 @@ MyBatis 技术内幕系列博客,从原理和源码角度,介绍了其内部
2525

2626
#### 3、最佳实践中,通常一个 Xml 映射文件,都会写一个 Dao 接口与之对应,请问,这个 Dao 接口的工作原理是什么?Dao 接口里的方法,参数不同时,方法能重载吗?
2727

28-
注:这道题也是京东面试官面试我时问的
28+
注:这道题也是京东面试官面试我被问的
2929

3030
答:Dao 接口,就是人们常说的 `Mapper`接口,接口的全限名,就是映射文件中的 namespace 的值,接口的方法名,就是映射文件中`MappedStatement`的 id 值,接口方法内的参数,就是传递给 sql 的参数。`Mapper`接口是没有实现类的,当调用接口方法时,接口全限名+方法名拼接字符串作为 key 值,可唯一定位一个`MappedStatement`,举例:`com.mybatis3.mappers.StudentDao.findStudentById`,可以唯一找到 namespace 为`com.mybatis3.mappers.StudentDao`下面`id = findStudentById``MappedStatement`。在 MyBatis 中,每一个`<select>``<insert>``<update>``<delete>`标签,都会被解析为一个`MappedStatement`对象。
3131

32-
Dao 接口里的方法,是不能重载的,因为是全限名+方法名的保存和寻找策略。
32+
~~Dao 接口里的方法,是不能重载的,因为是全限名+方法名的保存和寻找策略。~~
33+
34+
Dao 接口里的方法可以重载,但是Mybatis的XML里面的ID不允许重复。
35+
36+
Mybatis版本3.3.0,亲测如下:
37+
38+
```java
39+
/**
40+
* Mapper接口里面方法重载
41+
*/
42+
public interface StuMapper {
43+
44+
List<Student> getAllStu();
45+
46+
List<Student> getAllStu(@Param("id") Integer id);
47+
}
48+
```
49+
50+
然后在 `StuMapper.xml` 中利用Mybatis的动态sql就可以实现。
51+
52+
```java
53+
<select id="getAllStu" resultType="com.pojo.Student">
54+
select * from student
55+
<where>
56+
<if test="id != null">
57+
id = #{id}
58+
</if>
59+
</where>
60+
</select>
61+
```
62+
63+
能正常运行,并能得到相应的结果,这样就实现了在Dao接口中写重载方法。
64+
65+
**Mybatis 的 Dao 接口可以有多个重载方法,但是多个接口对应的映射必须只有一个,否则启动会报错。**
66+
67+
相关 issue :[更正:Dao 接口里的方法可以重载,但是Mybatis的XML里面的ID不允许重复!](https://github.com/Snailclimb/JavaGuide/issues/1122)
3368

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

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.