MyBatis源码学习环境准备
以下内容的公开课视频已经录制,需要的同学可留言
MyBatis
作为一个应用广泛的优秀的持久层ORM框架,已经成了JavaWeb世界近乎标配的部分,它支持定制化 SQL、存储过程以及高级映射。MyBatis
避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis
可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
1. 下载源码
下载最新的稳定版或者目前项目中使用的MyBatis
源代码,本课以MyBatis
3.5.1为例进行讲解,(目前最新版本为3.5.2-SNAPSHOT)。
下载地址: https://github.com/mybatis/mybatis-3
源码下载.png注意按照读tag进行版本选择。
2. 创建源码项目工程
下载源码后,在idea中导入pom工程,需要按照以下步骤进行修改调整,项目才能编译成功。
- pom文件中
ognl
、javassist
修改为<optional>false</optional>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.2.10</version>
<scope>compile</scope>
<optional>false</optional>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.24.1-GA</version>
<scope>compile</scope>
<optional>false</optional>
</dependency>
-
删除项目目录下的license.txt
如果不删除的话,在执行maven install时会出错。 -
手动下载jar包到本地
这个视情况而定,如果本地执行maven install时出现如下错误
[INFO] --- maven-surefire-plugin:2.7.1:test (default-test) @ wms ---
[WARNING] Error injecting: org.apache.maven.plugin.surefire.SurefirePlugin
java.lang.NoClassDefFoundError: org/apache/maven/surefire/util/NestedCheckedException
at java.lang.ClassLoader.defineClass1(Native Method)
则可以考虑手动下载对应jar包到本地maven仓库中。
-
关闭maven-pdf-plugin
<!-- <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pdf-plugin</artifactId> </plugin> -->
-
关闭test
执行maven install 时忽略test。
-
执行maven install
将
MyBatis
编译安装到本地maven仓库。
3. 搭建简单demo
从最简单的demo入手,前期先不要集成Spring,只看最简单的最原始的MyBatis
,熟悉了MyBatis
源码后再看如何与Spring集成;
结合官方文档搭建demo:http://www.mybatis.org/mybatis-3/zh/getting-started.html
基本使用流程
-
引入依赖
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
-
创建xml配置文件
mybatis-config.xml
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Cofig 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="EmployeeMapper.xml"></mapper> </mappers> </configuration>
EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.boxuegu.javaee.mybatissourcelearn.dao.EmployeeMapper"> <select id="getEmployeeById" resultType="com.boxuegu.javaee.mybatissourcelearn.dto.Employee"> select id,last_name lastname,gender, email from bxg_employee where id=#{id} </select> </mapper>
-
创建dto对象
Employee.java
package com.boxuegu.javaee.mybatissourcelearn.dto; /** * @author Jam Fang https://www.jianshu.com/u/0977ede560d4 * @version 创建时间:05.24 15:27 */ public class Employee { private Integer id; private String lastName; private String email; private String gender; @Override public String toString() { return "Employee{" + "id=" + id + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", gender='" + gender + '\'' + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
-
创建dao
EmployeeMapper.java
package com.boxuegu.javaee.mybatissourcelearn.dao; import com.boxuegu.javaee.mybatissourcelearn.dto.Employee; /** * @author Jam Fang https://www.jianshu.com/u/0977ede560d4 * @version 创建时间:05.24 17:32 */ public interface EmployeeMapper { public Employee getEmployeeById(Integer id); }
-
创建数据库测试表
-- ---------------------------- -- Table structure for bxg_employee -- ---------------------------- DROP TABLE IF EXISTS `bxg_employee`; CREATE TABLE `bxg_employee` ( `id` int(11) NOT NULL AUTO_INCREMENT, `last_name` varchar(255) DEFAULT NULL, `gender` char(1) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of bxg_employee -- ---------------------------- INSERT INTO `bxg_employee` VALUES ('1', 'zhangsan', '1', 'zhangsan@itcast.cn');
-
创建测试代码
package com.boxuegu.javaee.mybatissourcelearn; import com.boxuegu.javaee.mybatissourcelearn.dao.EmployeeMapper; import com.boxuegu.javaee.mybatissourcelearn.dto.Employee; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; /** * @author Jam Fang https://www.jianshu.com/u/0977ede560d4 * @version 创建时间:2019/6/17 13:16 */ public class Test { public static void main(String[] args) { //1.加载配置文件 String resource = "mybatis-config.xml"; InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(resource); } catch (IOException e) { e.printStackTrace(); } //2. 获取sqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //3. 获取sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); try { //4. 获取mapper接口实现 EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class); System.out.println("mapper::::" + mapper.getClass()); //5. 执行sql语句 Employee employee = mapper.getEmployeeById(1); System.out.println(employee); } finally { sqlSession.close(); } } }