Mybatis源码解析,一步一步从浅入深(一):创建准备工程

Spring SpringMVC Mybatis(简称ssm)是一个很流行的java web框架,而Mybatis作为ORM 持久层框架,因其灵活简单,深受青睐。而且现在的招聘职位中都要求应试者熟悉Mybatis框架。我认为有必要分析一下Mybatis的源码。在进行源码分析前,先准备一个简单的工程。如果你还不会使用maven请参考:Maven 创建项目之简单示例,创建一个简单的工程。

开发工具:eclipse

jdk版本:1.8

1,创建好的工程目录如下图所示:

  

2,现在来添加工程的依赖包,配置如下:

  

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.zcz</groupId>
  <artifactId>learnmybatis</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>learnmybatis</name>
  <description>learnmybatis</description>
  <dependencies>
      <!-- 添加junit -->
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
      </dependency>
      <!-- 添加log4j -->
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.16</version>
      </dependency>
      <!-- 添加mybatis -->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.2.6</version>
      </dependency>
      <!-- 添加mysql驱动 -->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.44</version>
      </dependency>
  </dependencies>
</project>

3,在src/main/resources中添加log4j配置log4j.properties,配置内容如下:

  

# priority  :debug<info<warn<error
#you cannot specify every priority with different file for log4j 
log4j.rootLogger=debug,stdout,info,debug,warn,error 
 
#console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
log4j.appender.stdout.layout.ConversionPattern= [%d{yyyy-MM-dd HH:mm:ss a}]:%p %l%m%n
#info log
log4j.logger.info=info
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender 
log4j.appender.info.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.info.File=./src/com/hp/log/info.log
log4j.appender.info.Append=true
log4j.appender.info.Threshold=INFO
log4j.appender.info.layout=org.apache.log4j.PatternLayout 
log4j.appender.info.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
#debug log
log4j.logger.debug=debug
log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender 
log4j.appender.debug.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.debug.File=./src/com/hp/log/debug.log
log4j.appender.debug.Append=true
log4j.appender.debug.Threshold=DEBUG
log4j.appender.debug.layout=org.apache.log4j.PatternLayout 
log4j.appender.debug.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
#warn log
log4j.logger.warn=warn
log4j.appender.warn=org.apache.log4j.DailyRollingFileAppender 
log4j.appender.warn.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.warn.File=./src/com/hp/log/warn.log
log4j.appender.warn.Append=true
log4j.appender.warn.Threshold=WARN
log4j.appender.warn.layout=org.apache.log4j.PatternLayout 
log4j.appender.warn.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n
#error
log4j.logger.error=error
log4j.appender.error = org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.DatePattern='_'yyyy-MM-dd'.log'
log4j.appender.error.File = ./src/com/hp/log/error.log 
log4j.appender.error.Append = true
log4j.appender.error.Threshold = ERROR 
log4j.appender.error.layout = org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss a} [Thread: %t][ Class:%c >> Method: %l ]%n%p:%m%n

 

4.接下来在src/main/resources中添加mybatis的配置文件configuration.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配置文件, 我这里面配置的是数据库相关 -->
  <properties resource="dbConfig.properties"></properties>
  
  <!-- 指定Mybatis使用log4j -->
  <settings>
     <setting name="logImpl" value="LOG4J"/>
  </settings>
      
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
          <!--
          如果上面没有指定数据库配置的properties文件,那么此处可以这样直接配置
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/learnMybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="123"/> -->
         
         
         <!-- 上面指定了数据库配置文件, 配置文件里面也是对应的这四个属性 -->
         <property name="driver" value="${driver}"/>
         <property name="url" value="${url}"/>
         <property name="username" value="${username}"/>
         <property name="password" value="${password}"/>
         
      </dataSource>
    </environment>
  </environments>
  
  <!-- 映射文件,mybatis精髓, 后面才会细讲 -->
  <mappers>
    <mapper resource="mapper/userDao-mapping.xml"/>
  </mappers>
  
</configuration>

5.然后在src/main/resources中添加数据库配置文件:dbConfig.properties,配置如下:

  

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/learnmybatis
username=root
password=123

6.在src/main/resources中添加mapper包,这个包中存放是的mybatis的mapper文件。

7.新建learnmybatis数据库,并创建表:user。表结构如图所示:

  

  插入一条数据:

  

8.准备工作完成,接下来就是代码实现了,我们先看一下这个时候的工程目录结构,如下图:

  

9.在src/main/java中新增包:com.zcz.learnmybatis.entity,并在次包下新增类User:

  

package com.zcz.learnmybatis.entity;

public class User {
    private int id;
    private String name;
    private String password;
    private int age;
    private int deleteFlag;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getDeleteFlag() {
        return deleteFlag;
    }
    public void setDeleteFlag(int deleteFlag) {
        this.deleteFlag = deleteFlag;
    }
}

10.在src/main/java中新增包:com.zcz.learnmybatis.dao,并在次包下新增类UserDao:

  

package com.zcz.learnmybatis.dao;

import java.util.List;

import com.zcz.learnmybatis.entity.User;

public interface UserDao {
    public void insert(User user);
    public User findUserById(int userId);
    public List<User> findAllUsers();
}

11,在mapper中新增userDao-mapping.xml文件:

  

<?xml version="1.0" encoding="UTF-8" ?>   
<!DOCTYPE mapper   
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"  
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> 
<mapper namespace="com.zcz.learnmybatis.dao.UserDao">

   <select id="findUserById" resultType="com.zcz.learnmybatis.entity.User" > 
      select * from user where id = #{id}
   </select>

</mapper>

12,在src/test/java中新增包:com.test.learnmybatis,并在次包下新增类:UserDaoTest:

  类中使用了@Test注解,不会使用的情查看 常用注解记录

package com.test.learnmybatis;

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 org.junit.Test;

import com.zcz.learnmybatis.dao.UserDao;
import com.zcz.learnmybatis.entity.User;

import junit.framework.Assert;

public class UserDaoTest {
    @Test
    public void finUserById() {
        SqlSession sqlSession = getSessionFactory().openSession();
        UserDao userMapper = sqlSession.getMapper(UserDao.class);
        User user = userMapper.findUserById(1);
        Assert.assertNotNull("not find", user);
        
    }
    
    private static SqlSessionFactory getSessionFactory() {
        SqlSessionFactory sessionFactory = null;
        String resource = "configuration.xml";
        try {
            sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return sessionFactory;
    }
}

13.到这里所有的准备工作已经完成了,现在看一下目录结构:

  

14.在UserDaoTest中右键->Run As->JUnit Test。可以看到,运行成功了:

  

15,到这里这个简单的mybatis就创建成功了,接下来就开始源码的跟踪与分析吧,接下来就是激动人心的时刻了 -------> Mybatis源码解析,一步一步从浅入深(二):按步骤解析源码

 

  工程已经上传github:https://github.com/ZCC1/learnmybatis.

  需要的伙伴可以去clone.


 

 

最后不得不提的是:在使用5.1.12版本的mysql驱动包的时候遇到了一个问题:Cause: java.sql.SQLException: Error setting driver on UnpooledDataSource. Cause: java.lang.ClassNotFoundException: Cannot find class: com.mysql.jdbc.Driver。

我另外写了一篇文章,给出了异常的详细内容和解决办法:Cannot find class: com.mysql.jdbc.Driver错误及解决办法。

 

 


  原创不易,转载请声明出处:https://www.cnblogs.com/zhangchengzi/p/9669707.html 

posted @ 2018-09-18 23:12  张橙子  阅读(2275)  评论(0编辑  收藏  举报