JAVAEE企业级框架(SSM)

1 篇文章 0 订阅
1 篇文章 0 订阅


前言

         使用MyBatis框架进行实际开发,只会简单的配置是不行的,我们还需要对框架中的核心对象核心配置文件以及映射文件有更深入的了解。本章将针对MyBatis核心对象、核心配置文件和映射文件进行解析。


  1. Mybatis官方文档

Mybatis官方学习文档https://mybatis.org/mybatis-3/zh/index.html

  •  使用Mybatis,只需将Mybatis-xxx.jar 文件置于类路径(classpath)中即可。
  • 如果使用Maven来构建项目,则需将以来代码放入pom.xml并刷新maven插件
  • <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>x.x.x</version>
    </dependency>
    

    2.从xml中构建SqlSesionFactor

每一个基于Mybatis的应用都是以一个SqlSessionFactory的实例为核心的。SqlSessionFactory的实例可以通过SqlSessionFactoryBuilder获得。而SqlSessionFactoryBuilder则可以从xml配置文件或一预先配置的Configuration实例来构建出SqlSessionFactory实例,例子如下:

//使用MyBatis提供的Rescources类加载MyBatis的配置文件
            Reader reader =
                    Resources.getResourceAsReader("mybatis-config.xml");
            //构建SqlSessionFactory工厂
            sqlSessionFactory =
                    new SqlSessionFactoryBuilder().build(reader);

 3.从xml文件中构建SqlSessionFactory

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>
<!--    环境配置-->
<!--    加载类路径下的属性文件-->
    <properties resource="db.properties"/>
<!--    <settings>-->
<!--        <setting name="loglmpl" value="S"/>-->
<!--    </settings>-->
    <environments default="development">
        <environment id="development">
<!--            配置运行环境的事务管理器-->
            <transactionManager type="JDBC"/>
<!--            数据库连接相关配置,dp.properties文件中的内容,动态获取db.propertise文件中的数据库连接信息-->
            <dataSource type="POOLED">
<!--                数据库驱动-->
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
    </environments>
<!--    mapping文件路径配置-->
    <mappers>
        <mapper resource="com/itheima/mapper/StudentMapper.xml"/>
<!--        <mapper resource="mapper/CustomerMapper.xml"/>-->
    </mappers>
</configuration>

 SqlSessionFactoryBuilder有5个build方法,每一种都允许你从不同的资源中创建一个SqlSessionFactory实例。

SqlSessionFactory build(InputStream inputStream, String environment)

SqlSessionFactory build(InputStream inputStream, Properties properties)

SqlSessionFactory build(InputStream inputStream, String env, Properties props)

可选的参数是 environment 和 properties。environment 决定加载哪种环境,包括数据源和事务管理器,参考文档中有详细说明。

4.SqlSessionFactoryBuilder构建Builde方法的形式。

 sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

 由于Build方法中的参数environment和properties都可以为null,所以SqlSessionFactoryBuild构建SqlSessionFactory对象的build()方法按照配置信息的传入方式,为3种:

4.1SqlSessionFactoryBuilder构建build方法

build(InputStream inputStream,String environment,Properties properties);

上述build方法种,参数inputStream是字节流,它它封装了XML文件形式的配置信息;参数environment和参数properties为可选参数。其中,参数environment决定将要加载的环境,包括数据源事务管理器;参数properties决定将要加载的properties文件 

 4.2SqlSessionFactoryBuilder构建build方法

build(Reader reader,String environment,Properties properties)

由上述build()方法可知,第二种形式的build()方法参数作用与第一种形式大体一致,唯一不同的是,第一种形式的build()方法使用InputStream字节流封装了XML文件形式的配置信息,而第二种形式的build()方法使用Reader字符流封装了xml文件形式的配置信息  

4.3SqlSessionFactoryBuilder构建build()方法 

build(Configuration config)

通过以上代码可知,配置信息可以通过InputStream(字节流)、Reader(字符流)、Configuration(类)三种形式提供给SqlSessionFactoryBuilderbuild()方法。

5.使用什么模式创建SqlSessionFactory对象

         SqlSessionFactory对象是线程安全的,它一旦被创建,在整个应用程序执行期间都会存在。如果我们多次创建同一个数据库的SqlSessionFactory对象,那么该数据库的资源将很容易被耗尽。通常每一个数据库都只创建一个SqlSessionFactory对象,所以在构建SqlSessionFactory对象时,建议使用单例模式

方法名称

描述

SqlSession openSession()

开启一个事务。

SqlSession openSession(Boolean autoCommit)

参数autoCommit可设置是否开启事务。

SqlSession openSession(Connection connection)

参数connection可提供自定义连接。

SqlSession openSession(TransactionIsolationLevel  level)

参数level可设置隔离级别。

SqlSession openSession(ExecutorType execType)

参数execType有三个可选值。

SqlSession openSession(ExecutorType  execType

Boolean  autoCommit)

参数execType有三个可选值。

SqlSession openSession(ExecutorType  execType,                 

Connection connection)

参数ExecutorType有三个可选值。

openSession(ExecutorType execType)参数值

    参数execType有三个可选值:

ExecutorType.SIMPLE :表示为每条语句创建一条新的预处理语句。
ExecutorType.REUSE :表示会复用预处理语句。
ExecutorType.BATCH :表示会批量执行所有更新语句。

openSession(ExecutorType  execType,Boolean  autoCommit)参数值  

参数 execType 有三个可选值,同 openSession(ExecutorType execType)的参数。
参数 autoCommit 可设置是否开启事务

openSession(ExecutorType  execType,Connection connection)参数值

参数 execType 有三个可选值,同openSession(ExecutorType execType)的参数。
参数 connection 可提供自定义连接

SqlSession对象的作用 

SqlSessionMyBatis框架中另一个重要的对象,它是应用程序与持久层之间执行交互操作的一个单线程对象,主要作用是执行持久化操作,类似于JDBC中的ConnectionSqlSession对象包含了执行SQL操作的方法,由于其底层封装了JDBC连接,所以可以直接使用SqlSession对象来执行已映射的SQL语句  

方法名称

描述

<T> T selectOne(String statement)

查询方法。参数statement是在配置文件中定义的<select>元素的id。

<T> T selectOne(String statement, Object parameter)

查询方法。parameter是查询语句所需的参数。

<E> List<E> selectList(String statement)

查询方法。参数statement是在配置文件中定义的<select>元素的id。

<E> List<E> selectList(String statement, Object parameter)

查询方法。parameter是查询语句所需的参数

<E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds)

查询方法。rowBounds是用于分页的参数对象

void select(String statement, Object parameter, ResultHandler handler)

查询方法。,handler对象用于处理查询语句返回的复杂结果集

int insert(String statement)

插入方法。参数statement是在配置文件中定义的<insert>元素的id。

int insert(String statement, Object parameter)

插入方法。parameter是插入语句所需的参数

int update(String statement)

更新方法。参数statement是在配置文件中定义的<update>元素的id

int update(String statement, Object parameter)

更新方法。parameter是更新语句所需的参数

int delete(String statement)

删除方法。参数statement是在配置文件中定义的<delete>元素的id

void commit()

提交事务的方法。

void rollback()

回滚事务的方法。

void close()

关闭SqlSession对象。

<T> T getMapper(Class<T> type)

该方法会返回Mapper接口的代理对象。参数type是Mapper的接口类型。

Connection getConnection()

获取JDBC数据库连接对象的方法

补充:使用Mapper接口

/**
* MyBatis基于Mapper接口的使用,需要遵守相关的约定*
*1.声明的接口方法名必须要和映射文件中的SQL语句id一致
*2.映射文件中namespace必须是接口的全类路径名称
*3.接口的名称必须要和映射文件的名称相同**/
public interface UserMapper 
{
public User findById(Integer id);
}
/**
* 基于Mapper接口的实现*/
@Test
public void query() throws Exception
{
InputStream in = Resources.getResourceAsStream("mybatis-config.xmL");
SqLSessionFactory factory = new SqLSessionFactoryBuilder().build(in);
SqLSession sqLSession = factory.openSession();
UserMapper mappelr = sqLSession.getMapper(UserMapper.cLass);
User user = mapper.findById(2);
System.out.println(user.getUname());
session.close();
}

总结

以上就是对Mybatis核心对象(SqlSessionFactory、SqlSessionFactoryBuilder、SqlSession)作用的理解,参考于人民邮电出版社JavaEE企业级应用开发教程。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无敌暴龙兽7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值