chapter-3--mybatis的核心组件

一、SqlSessionFactory

1、类接口关系

SqlSessionFactorySqlSession接口对象的生成工厂,而SqlSessionFactory接口对象又由SqlSessionFactoryBuilder采用建造者模式借助Configuration配置类来生成。

chapter-3--mybatis的核心组件_第1张图片
SqlSessionFactory的生成

SqlSessionFactory有两个实现类,分别是DefaultSessionFactory和SqlSessionManagerSqlSessionManager适合于在多线程情况下使用。

2、采用xml配置文件生成SqlSessionFactory接口对象

  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

  "http://mybatis.org/dtd/mybatis-3-config.dtd">

 

   

   

     

     

     

     

   

   

   

     

   

   

   

     

     

   

   

   

     

   

   

   

   

       

       

         

         

         

         

       

     

   

   

   

     

     

   

 

读取配置文件并生成SqlSessionFactory接口对象:

private static final String RESOURCE = "mybatis-config.xml";

private  static SqlSessionFactory factory;//单例模式

InputStream iStream = null;

try {

iStream = Resources.getResourceAsStream(RESOURCE);

factory = new SqlSessionFactoryBuilder().build(iStream);

} catch (IOException e) {

e.printStackTrace();

}

二、SqlSession接口

1、类接口关系

SqlSession接口对象类似JDBC中的Connection对象,代表着一个连接资源的启用,它的主要功能如下:

(1)、获取Mapper接口对象: RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);

(2)、发送SQL给数据库。

(3)、控制数据库事务

SqlSession接口有两个实现类,分别是DefaultSqlSession和SqlSessionManager


chapter-3--mybatis的核心组件_第2张图片

2、获取SqlSession接口对象

//定义SqlSession接口对象

SqlSession sqlSession = null;

try{

//打开SqlSession会话

sqlSession = SqlSessionFactory.openSession();

//do something

sqlSeesion.commit(); //提交事务

}catch(Exception ex){

sqlSession.rollback(); //回滚事务

}finally{

//在finally语句中确保资源被顺利关闭

if(sqlSession != null){

sqlSession.close();

}

}

三、Mapper(映射器)

1、组成和功能

映射器由一个接口和对应xml配置文件或则注解组成,其主要功能如下:

(1)通过resultMap描述映射规则。

(2)提供SQL语句,并可以配置SQL参数类型、返回类型、缓存刷新等信息。

(3)配置缓存。

(4)提供动态SQL。

总结,它的主要功能就是将SQL查询到的结果映射为POJO对象,或者将POJO数据插入到数据库中,并定义一些关于缓存等的重要内容。

2、通过xml配置文件配置映射器

在SqlSessionFactory的配置文件中有这样一个属性就是引入映射器的配置文件

     

     

   

映射器的配置文件:


PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

 

    insert into t_role(role_name, note) values(#{roleName}, #{note})

 

 

    delete from t_role where id=#{id}

 

 

    update t_role set role_name=#{roleName}, note=#{note} where id=#{id}

 

 

 

 

四、生命周期


chapter-3--mybatis的核心组件_第3张图片

1、SqlSessionFactoryBuilder

它的作用就是创建SqlSessionFactory,所以它只能存在于创建SqlSessionFactory的方法中而不能让其长期存在。

2、SqlSessionFactory

SqlSessionFactory可以被认为是一个数据库连接池,它的作用是创建SqlSession接口对象。MyBatis的本质是Java对数据库的操作所以SqlSessionFactory的生命周期存在于整个MyBatis的应用之中,进而可以认为SqlSessionFactory的生命周期等同于MyBatis的应用周期。

3、SqlSession

SqlSession相当于一个数据库连接(Connection对象),它存活一次完整的业务请求中,处理完请求后应该关闭这条连接,归还给SqlSessionFactory,避免数据库连接资源被耗尽。

4、Mapper

Mapper由SqlSession接口对象所创建,所以它的生命周期小于等于SqlSession的生命周期。

你可能感兴趣的:(chapter-3--mybatis的核心组件)