IDEA环境使用Maven搭建第一个MyBatis程序

IDEA环境使用Maven搭建第一个MyBatis程序

  • 一、项目创建
    • 1.1 创建空项目
    • 1.2 新建Module(MyBatisDemo)
      • 1.2.1 项目结构
      • 1.2.2 引入MyBatis坐标
      • 1.2.3 引入MyBatis所依赖的其他jar包坐标
      • 1.2.4 创建配置文件
        • 1.2.4.1 主配置文件
        • 1.2.4.2 创建映射文件
      • 1.2.4.3 引入约束文件
      • 1.2.4.4 日志配置文件
    • 1.3 创建数据库表
    • 1.4 基本程序编写
      • 1.4.1 创建测试类
      • 1.4.2 创建java实体类
      • 1.4.3 创建dao接口
      • 1.4.4 定义Dao的实现类
    • 1.5 进行测试
  • 二、项目完善
    • 1、如果只想在日志中显示指定命名空间的内容
    • 2、写工具类,简化代码
    • 3、属性文件配置jdbc四要素
  • 三、源码分析
    • 1、输入流的关闭
    • 2、SqlSession的创建
    • 3、增删改的执行
    • 4、SqlSession的提交commit()
    • 5、SqlSession的关闭

一、项目创建

1.1 创建空项目

IDEA环境使用Maven搭建第一个MyBatis程序_第1张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第2张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第3张图片

1.2 新建Module(MyBatisDemo)

IDEA环境使用Maven搭建第一个MyBatis程序_第4张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第5张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第6张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第7张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第8张图片

1.2.1 项目结构

IDEA环境使用Maven搭建第一个MyBatis程序_第9张图片

1.2.2 引入MyBatis坐标

MyBatis需要引用的jar包:
IDEA环境使用Maven搭建第一个MyBatis程序_第10张图片
maven官网(https://mvnrepository.com/)查询Maven引入MyBatis依赖代码信息
IDEA环境使用Maven搭建第一个MyBatis程序_第11张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第12张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第13张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第14张图片

1.2.3 引入MyBatis所依赖的其他jar包坐标

所有依赖:

<dependencies>

    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.4.6version>
    dependency>

    <dependency>
      <groupId>cglibgroupId>
      <artifactId>cglibartifactId>
      <version>3.2.5version>
    dependency>

    <dependency>
      <groupId>org.ow2.asmgroupId>
      <artifactId>asmartifactId>
      <version>5.2version>
    dependency>

    <dependency>
      <groupId>commons-logginggroupId>
      <artifactId>commons-loggingartifactId>
      <version>1.2version>
    dependency>

    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>1.2.17version>
    dependency>

    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-apiartifactId>
      <version>2.3version>
    dependency>

    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.6version>
    dependency>
    
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-coreartifactId>
      <version>2.3version>
    dependency>

    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>1.7.25version>
    dependency>

    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>1.7.25version>
      <scope>testscope>
    dependency>

    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>
  dependencies>

1.2.4 创建配置文件

1.2.4.1 主配置文件

IDEA环境使用Maven搭建第一个MyBatis程序_第15张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第16张图片
mybatis.xml



<configuration>
    
    <environments default="testEM">
        
        <environment id="onlineEM">
            
            <transactionManager type="JDBC">transactionManager>

            
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            dataSource>
        environment>

        
        <environment id="testEM">
            
            <transactionManager type="JDBC">transactionManager>

            
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            dataSource>
        environment>

    environments>

    
    <mappers>
        <mapper resource="com/aoing/dao/mapper.xml">mapper>
    mappers>

configuration>
1.2.4.2 创建映射文件

IDEA环境使用Maven搭建第一个MyBatis程序_第17张图片
mapper.xml



<mapper namespace="xxx">
    <insert id="insertStudent" parameterType="com.aoing.bean.Student">
        insert into student(name,age,score) value(#{name},#{age},#{score})/*必须要和属性同名*/
    insert>
mapper>

1.2.4.3 引入约束文件

IDEA环境使用Maven搭建第一个MyBatis程序_第18张图片

IDEA环境使用Maven搭建第一个MyBatis程序_第19张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第20张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第21张图片

IDEA环境使用Maven搭建第一个MyBatis程序_第22张图片

1.2.4.4 日志配置文件

log4j.properties

log4j.rootLogger=debug, console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern= %d{hh:mm:ss,SSS} [%t] %-5p %c %x - %m%n

1.3 创建数据库表

IDEA环境使用Maven搭建第一个MyBatis程序_第23张图片
建表语句:test.sql


CREATE DATABASE `test`;

USE `test`;

/*Table structure for table `student` */

DROP TABLE IF EXISTS `student`;

CREATE TABLE `student` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `score` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

insert  into `student`(`id`,`name`,`age`,`score`) values (1,'张三',23,93.5),(2,'李四',24,94.5),(3,'王五',25,95.5);

1.4 基本程序编写

1.4.1 创建测试类

package com.aoing;

import com.aoing.bean.Student;
import com.aoing.dao.StudentDao;
import com.aoing.dao.StudentDaoImpl;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;


public class MyTest_log4j
{
    private static Logger logger = Logger.getLogger(MyTest_log4j.class);
    
    private StudentDao dao;

    @Before
    public void before(){
        dao = new StudentDaoImpl();
    }

    @Test
    public void testInsert()
    {
        Student student = new Student("小明", 24, 90);
        dao.insertStudent(student);
        logger.info("插入数据库");
    }
}

1.4.2 创建java实体类

package com.aoing.bean;

public class Student {
    private Integer id;
    private String name;
    private int age;
    private double score;

    public Student(String name, int age, double score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }
}

注意:属性和成员变量不一样
IDEA环境使用Maven搭建第一个MyBatis程序_第24张图片

1.4.3 创建dao接口

package com.aoing.dao;

import com.aoing.bean.Student;

public interface StudentDao {
    void insertStudent(Student student);
}

1.4.4 定义Dao的实现类

package com.aoing.dao;

import com.aoing.bean.Student;
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;

public class StudentDaoImpl implements StudentDao {

    private SqlSession sqlSession;

    @Override
    public void insertStudent(Student student) {
        try{
            //加载主配置文件
            InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");

            //创建SqlSessionFactory对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            //创建SqlSession对象
            sqlSession = sqlSessionFactory.openSession();

            //进行增删改查
            sqlSession.insert("insertStudent",student);

            //提交事务
            sqlSession.commit();
        } catch (IOException e){
            e.printStackTrace();
        } finally{
            if(sqlSession != null){
                sqlSession.close();
            }
        }
    }
}

1.5 进行测试

使用junit运行测试类MyTest_log4j的testInsert方法
IDEA环境使用Maven搭建第一个MyBatis程序_第25张图片
查看数据库:
IDEA环境使用Maven搭建第一个MyBatis程序_第26张图片

二、项目完善

1、如果只想在日志中显示指定命名空间的内容

IDEA环境使用Maven搭建第一个MyBatis程序_第27张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第28张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第29张图片

2、写工具类,简化代码

IDEA环境使用Maven搭建第一个MyBatis程序_第30张图片
MyBatisUtils.java

package com.aoing.utils;

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;

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    public static SqlSession getSqlSession(){
        try {
            InputStream is = Resources.getResourceAsStream("mybatis.xml");
            //设为单例模式
            if (sqlSessionFactory == null) {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            }
            return sqlSessionFactory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

修改StudentDaoImpl.java文件
IDEA环境使用Maven搭建第一个MyBatis程序_第31张图片

package com.aoing.dao;

import com.aoing.bean.Student;
import com.aoing.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

public class StudentDaoImpl implements StudentDao {

    private SqlSession sqlSession;

    @Override
    public void insertStudent(Student student) {
        try{
            //创建SqlSession对象
            sqlSession = MyBatisUtils.getSqlSession();

            //进行增删改查
            sqlSession.insert("insertStudent",student);

            //提交事务
            sqlSession.commit();
        } finally{
            if(sqlSession != null){
                sqlSession.close();
            }
        }
    }
}

3、属性文件配置jdbc四要素

IDEA环境使用Maven搭建第一个MyBatis程序_第32张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第33张图片
mybatis.xml



<configuration>
    <properties resource="jdbc_mysql.properties"/>
    
    <environments default="onlineEM">
        
        <environment id="onlineEM">
            
            <transactionManager type="JDBC">transactionManager>

            
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            dataSource>
        environment>

        
        <environment id="testEM">
            
            <transactionManager type="JDBC">transactionManager>

            
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            dataSource>
        environment>

    environments>

    
    <mappers>
        <mapper resource="mapper.xml">mapper>
    mappers>

configuration>

jdbc_mysql.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test
jdbc.username=root
jdbc.password=123

三、源码分析

1、输入流的关闭

在输入流对象使用完毕后,不用手工进行流的关闭。因为输入流在使用完毕后,SqlSessionFactoryBuilder对象的build()方法会自动将输入流关闭。
IDEA环境使用Maven搭建第一个MyBatis程序_第34张图片

2、SqlSession的创建

使用SqlSessionFactory 接口对象的openSession()方法创建SqlSession对象,SqlSessionFactory 接口的实现类为DefaultSqlSessionFactory。
IDEA环境使用Maven搭建第一个MyBatis程序_第35张图片
openSession()方法的源码:
IDEA环境使用Maven搭建第一个MyBatis程序_第36张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第37张图片
由上看出,无参的openSession()方法,将事务的自动提交直接赋值为false。创建SqlSession就是加载了主配置文件,创建一个执行器对象(将来用于执行映射文件中的SQl语句),初始化了一个DB数据被修改的标志变量dirty,关闭了事务的自动提交功能。

3、增删改的执行

对于SqlSession的insert|()、delete()、update()方法,底层均是调用执行了update()方法。
IDEA环境使用Maven搭建第一个MyBatis程序_第38张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第39张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第40张图片
增删改操作均是对数据进行修改,均是将dirty变量设置为true,并且在获取到的映射文件中指定id的SQL语句后,由执行器executor执行。

4、SqlSession的提交commit()

IDEA环境使用Maven搭建第一个MyBatis程序_第41张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第42张图片
isCommitOrRollbackRequired(force)方法的返回值为true。继续跟踪executor的commit()方法:
IDEA环境使用Maven搭建第一个MyBatis程序_第43张图片
IDEA环境使用Maven搭建第一个MyBatis程序_第44张图片
执行SqlSession的无参commit()方法,最终会将事务进行提交。

5、SqlSession的关闭

IDEA环境使用Maven搭建第一个MyBatis程序_第45张图片
在这里插入图片描述
isCommitOrRollbackRequired(force)方法的返回值为true,继续跟踪executor的close()方法:
IDEA环境使用Maven搭建第一个MyBatis程序_第46张图片
再跟踪Executor接口的BaseExecutor抽象类的close()方法:
在这里插入图片描述
IDEA环境使用Maven搭建第一个MyBatis程序_第47张图片
在SqlSession进行关闭时,会将事务回滚后关闭。所以对于MyBatis程序,无需通过显式地对SqlSession进行回滚,达到事务回滚的目的。

你可能感兴趣的:(Demo样例)