Mybatis源码分析(1)---mybatis简单入门

1. 什么是 MyBatis?

这里我们直接引用MyBatis官网介绍:
在这里插入图片描述
详细的mybatis使用以及文档介绍,大家可以直接在mybatis官网了解和学习
下面我们搭建mybatis的demo工程mybatisCode,它将作为整个mybatis系列源码分析工程,通过我们平时使用mybatis的运行过程,一层一层的解析mybatis的源码以及原理

2. 搭建mybatis的mybatisCode工程

2.1 目录结构

Mybatis源码分析(1)---mybatis简单入门_第1张图片

2.2 工程代码搭建
2.2.1 log4j.properties文件
log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
2.2.2 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>
  <environments default="mysql">
    <environment id="mysql">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
      </dataSource>
    </environment>
  </environments>
  
  <mappers>
    <mapper resource="mapper/UserMapper.xml"/>
  </mappers>
</configuration>
2.2.3 pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mybatis.lean</groupId>
  <artifactId>mybatisCode</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>mybatisCode Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>  
	<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
	<dependency>
	    <groupId>org.mybatis</groupId>
	    <artifactId>mybatis</artifactId>
	    <version>3.5.1</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>8.0.15</version>
	</dependency>
	
	<!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>mybatisCode</finalName>
  </build>
</project>

2.2.4 数据库创建user表

在mysql中创建数据库test,在test库中创建user表

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` varchar(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
)
2.2.4 创建User类
	
	private Integer id;
	private String name;
	private Integer age;
	private String sex;
	//具体的set,get方法
	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
2.2.5 创建UserMapper映射接口
	//暂时只有一个查询方法
	User findUserById(Integer id);
2.2.6 创建UserMapper.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="mapper.UserMapper">
	<select id="findUserById" resultType="pojo.User" parameterType="java.lang.Integer">
		select * from user where id= #{id}
	</select>
</mapper>
2.2.7 创建UserTest测试类
	private SqlSessionFactory sqlSessionFactory = null;
	
	@Before
	public void before() throws IOException{
		InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}
	
	@Test
	public void findUserById() throws IOException{
		SqlSession sqlSession = sqlSessionFactory.openSession();
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = userMapper.findUserById(1);
		System.out.println(user);
	}
3 运行测试

通过运行测试类,我们成功的获取了id为1的User对象,对象的内容:User [id=1, name=lin, age=20, sex=0]
这里大概介绍一下整个mybatis加载运行的过程:

  1. 通过获取mybatis-config.xml配置文件的输入流inputStream
  2. SqlSessionFactoryBuilder类使用输入流创建了sqlSessionFactory,见名知意,就是创建了sqlSession的工厂类,通过sqlSessionFactory创建了sqlSession,然后通过getMapper(Class type)获取UserMapper的代理对象,执行了接口方法findUserById(int id)
  3. 把查询的数据封装在User对象中
    Mybatis源码分析(1)---mybatis简单入门_第2张图片
    下篇开始Mybatis源码分析(2)—初始化配置文件,我们通过SqlSessionFactoryBuilder类开始,在mybatisCode工程中深入了解mybatis源码,分析mybatis源码内部的运行

你可能感兴趣的:(Mybatis,mybatis源码,源码分析)