MyBatis - debugging environment to build
1. rely tool
- Maven
- Git
- JDK
- IntelliJ IDEA
2. Source pull
From the official repository https://github.com/mybatis/mybatis-3 Fork
a warehouse of their own. Why Fork
? Since the beginning of reading, debugging source code, we might write some notes, have their own warehouses, can be freely submitted.
Using IntelliJ IDEA
from Fork
out of the warehouse pull code.
MyBatis version of this article used to 3.5.0-SNAPSHOT
.
3. Debugging
MyBatis want to debug, very convenient, only need to open the org.apache.ibatis.autoconstructor.AutoConstructorTest
unit test class, any one of the unit test method, right, you can start debugging.
Of course, taking into account so that we better understand AutoConstructorTest this class, the following, we resolve detail below. AutoConstructorTest located in autoconstructor
the package, the overall structure is as follows:
4. mybatis-config.xml
mybatis-config.xml
, MyBatis configuration file. XML is as follows:
|
- 在
<environments />
标签中,配置了事务管理和数据源。考虑到减少外部依赖,所以使用了 HSQLDB 。 - 在
<mappers />
标签中,配置了需要扫描的 Mapper 文件。目前,仅仅扫描AutoConstructorMapper.xml
文件。
5. AutoConstructorMapper.xml
AutoConstructorMapper.xml
,Mapper 文件。代码如下:
|
- 对应的接口为
org.apache.ibatis.autoconstructor.AutoConstructorMapper
。
5.1 AutoConstructorMapper
public interface AutoConstructorMapper { |
- 使用注解的方法,编写 SQL 。
6. CreateDB.sql
CreateDB.sql
文件,用于单元测试里,初始化数据库的数据。如下:
DROP TABLE subject |
- 创建了
subject
表,并初始化三条数据。 - 创建了
extensive_subject
表,并初始化三条数据。
7. POJO
在 AutoConstructorMapper 中,我们可以看到有四个 POJO 类。但是,从 CreateDB.sql
中,实际只有两个表。这个是为什么呢?继续往下看噢。
7.1 AnnotatedSubject
package org.apache.ibatis.autoconstructor; |
- 对应
subject
表。 @AutomapConstructor
注解,表示 MyBatis 查询后,在创建 AnnotatedSubject 对象,使用该构造方法。
7.1.1 PrimitiveSubject
package org.apache.ibatis.autoconstructor; |
- 对应的也是
subject
表。 - 和 AnnotatedSubject 不同,在其构造方法上,
weight
和height
方法参数的类型是int
,而不是 Integer 。那么,如果subject
表中的记录,这两个字段为NULL
时,会创建 PrimitiveSubject 对象报错。
7.1.2 BadSubject
package org.apache.ibatis.autoconstructor; |
- 对应的也是
subject
表。 - 和 AnnotatedSubject 不同,在其构造方法上,
height
方法参数的类型是 Height ,而不是 Integer 。因为 MyBatis 无法识别 Height 类,所以会创建 BadSubject 对象报错。
7.2 ExtensiveSubject
package org.apache.ibatis.autoconstructor; |
- 对应的也是
extensive_subject
表。 - 这是个复杂对象,基本涵盖了各种类型的数据。
8. AutoConstructorTest
org.apache.ibatis.autoconstructor.AutoConstructorTest
,单元测试类。
8.1 setUp
private static SqlSessionFactory sqlSessionFactory; |
- Creating a SqlSessionFactory, based on
mybatis-config.xml
the configuration file. - The initial data into memory database based on
CreateDB.sql
SQL file.