一、mybatis源码编译
1.下载mybatis源码,地址:https://github.com/mybatis/mybatis-3
2.将下载的源码包通过idea打开,如图所示:
点击open,弹出如下窗口:
选择源码包,然后点击ok,等待构建,构建过程比较耗时。
二、编写测试用例
测试用例需要文件: 自己定义的java测试包及java文件, resource包(mybatis-config.xml, config.properties), mapper.xml文件
目录结构如下:
1. mybatis-config.xml如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="com/mamba/resource/config.properties"></properties>
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<!-- <setting name="aggressiveLazyLoading" value="false"/> -->
</settings>
<typeAliases>
<typeAlias alias="role" type="com.mamba.po.Role"/>
</typeAliases>
<typeHandlers>
<typeHandler jdbcType="VARCHAR" javaType="string" handler="com.mamba.handler.MyStringHandler"/>
</typeHandlers>
<!-- 定义数据库的信息,默认使用development数据库构建环境 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<!--<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis-test?useSSL=false" />
<property name="username" value="root" />
<property name="password" value="xxxxx" />-->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<!-- 定义映射器 -->
<mappers>
<package name="com.mamba.mapper"/>
</mappers>
</configuration>
配置文件的元素具体介绍可参考mybatis官方网站:https://mybatis.org/mybatis-3/zh/configuration.html
2. config.properties文件主要提供动态参数,便于管理。如下:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis-test?useSSL=false
username=root
password=xxxx
在mybatis-config.xml中就可以使用${}形式动态读取。
3. mainTest代码:
public class MainTest {
public static void main(String[] args) {
String resource = "com/mamba/resource/mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = null;
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
Role role = roleMapper.getRole(1L);
System.out.println(role.getId() + ":" + role.getRoleName() + ":" + role.getNote());
sqlSession.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
sqlSession.rollback();
e.printStackTrace();
} finally {
sqlSession.close();
}
}
}
这样,测试用例建立的过程大致就是这样。
注意,源码是没有引入mysql驱动包的,需要在pom.xml中增加一下:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>