关于Mybatis的一些基本知识


Mybatis  一款轻量级持久层框架

Mybatis在idea中的使用步骤:

  1. 创建maven工程,引入对应的maven坐标。
    <dependency>
       <groupId>org.mybatisgroupId>
       <artifactId>mybatisartifactId>
       <version>3.5.2version>
    dependency>
    <dependency>
       <groupId>mysqlgroupId>
       <artifactId>mysql-connector-javaartifactId>
       <version>5.1.47version>
    dependency>
  2. 创建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="development">
           <environment id="development">
               <transactionManager type="JDBC"/>
               <dataSource type="POOLED">
                   <property name="driver" value="com.mysql.jdbc.Driver"/>
                   <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8"/>
                   <property name="username" value="root"/>
                   <property name="password" value="123456"/>
               dataSource>
           environment>
       environments>
       <mappers>
           <mapper resource="com/kuang/dao/userMapper.xml"/>
       mappers>
    configuration>
  3.  使用Resources.getResourceAsStream()方法获取配置文件流,使用SqlSessionFactoryBuilder对象的build()方法读取流,并且得到SqlSessionFactory对象,此对象的openSession()方法可以用来生产sqlsession对象。
    public class MybatisUtils {
    
       private static SqlSessionFactory sqlSessionFactory;
    
       static {
           try {
               String resource = "mybatis-config.xml";
               InputStream inputStream = Resources.getResourceAsStream(resource);
               sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
          } catch (IOException e) {
               e.printStackTrace();
          }
      }
    
       //获取SqlSession连接
       public static SqlSession getSession(){
           return sqlSessionFactory.openSession();
      }
    
    }

  4. 创建持久层接口xxxMapper,并定义需要使用的方法。
    public interface UserMapper {
       List selectUser();
    }
  5. 通过sqlsession对象的getMapper()方法获取持久层接口,执行接口中的方法。
    public class MyTest {
       @Test
       public void selectUser() {
           SqlSession session = MybatisUtils.getSession();
           //方法一:
           //List users = session.selectList("com.kuang.mapper.UserMapper.selectUser");
           //方法二:
           UserMapper mapper = session.getMapper(UserMapper.class);
           List users = mapper.selectUser();
    
           for (User user: users){
               System.out.println(user);
          }
           session.close();
      }
    }
  6. 运行测试。

    可能会存在maven静态资源过滤问题,使用以下方法解决:
    <resources>
       <resource>
           <directory>src/main/javadirectory>
           <includes>
               <include>**/*.propertiesinclude>
               <include>**/*.xmlinclude>
           includes>
           <filtering>falsefiltering>
       resource>
       <resource>
           <directory>src/main/resourcesdirectory>
           <includes>
               <include>**/*.propertiesinclude>
               <include>**/*.xmlinclude>
           includes>
           <filtering>falsefiltering>
       resource>
    resources>

mybatis中的各种标签:select、insert、update、delete......

以及标签中各种参数:parameterType   resultType......以及基本类型在标签中对应的写法

 注意点:当使用sqlsessionFactory对象获取sqlsession对象时,未设置自动提交事务,即未能:sqlSessionFactory.openSession(true);在增删改时需要手动提交事务,否则无法生效。sqlsession对象用完后记得关闭!!!

小结:

  • 所有的增删改操作都需要提交事务!

  • 接口所有的普通参数,尽量都写上@Param参数,尤其是多个参数时,必须写上!

  • 有时候根据业务的需求,可以考虑使用map传递参数!

  • 为了规范操作,在SQL的配置文件中,我们尽量将Parameter参数和resultType都写上!

配置文件解析(重点)

configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)

environments元素:
  
<environments default="development">
 <environment id="development">
   <transactionManager type="JDBC">
     <property name="..." value="..."/>
   transactionManager>
   <dataSource type="POOLED">
     <property name="driver" value="${driver}"/>
     <property name="url" value="${url}"/>
     <property name="username" value="${username}"/>
     <property name="password" value="${password}"/>
   dataSource>
 environment>
environments>
environments可以配置多套运行环境,将sql映射到不同的数据库上,必须通过default指定一个默认的运行环境。
  子节点元素environment:
  • dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。
  • 数据源是必须配置的。
  • 有三种内建的数据源类型 type="[UNPOOLED|POOLED|JNDI]")
  • unpooled:这个数据源的实现只是每次被请求时打开和关闭连接。
  • pooled:这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来 , 这是一种使得并发 Web 应用快速响应请求的流行处理方式。
  • jndi:这个数据源的实现是为了能在如 Spring 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的引用。
  • 数据源也有很多第三方的实现,比如dbcp,c3p0,druid等等....
  • 详情:点击查看官方文档
  • 这两种事务管理器类型都不需要设置任何属性。
  • 具体的一套环境,通过设置id进行区别,id保证唯一!
  • 子元素节点:transactionManager - [ 事务管理器 ]
  • 子元素节点:数据源(dataSource)

   mapper元素:
  • 映射器 : 定义映射SQL语句文件

  • 既然 MyBatis 的行为其他元素已经配置完了,我们现在就要定义 SQL 映射语句了。但是首先我们需要告诉 MyBatis 到哪里去找到这些语句。Java 在自动查找这方面没有提供一个很好的方法,所以最佳的方式是告诉 MyBatis 到哪里去找映射文件。你可以使用相对于类路径的资源引用, 或完全限定资源定位符(包括 file:/// 的 URL),或类名和包名等。映射器是MyBatis中最核心的组件之一,在MyBatis 3之前,只支持xml映射器,即:所有的SQL语句都必须在xml文件中配置。而从MyBatis 3开始,还支持接口映射器,这种映射器方式允许以Java代码的方式注解定义SQL语句,非常简洁。

引入mapper资源的方式:


<mappers>
 <mapper resource="org/mybatis/builder/PostMapper.xml"/>
mappers>


<mappers>
 <mapper url="file:///var/mappers/AuthorMapper.xml"/>
mappers>


<mappers>
 <mapper class="org.mybatis.builder.AuthorMapper"/>
mappers>



<mappers>
 <package name="org.mybatis.builder"/>
mappers>

Mapper文件(可以想象成是具体实现类,实现CRUD方法):

<?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="com.kuang.mapper.UserMapper">
   
mapper>
  • namespace中文意思:命名空间,作用如下:

    • namespace的命名必须跟某个接口同名

    • 接口中的方法与映射文件中sql语句id应该一一对应

    1. namespace和子元素的id联合保证唯一  , 区别不同的mapper

    2. 绑定DAO接口

    3. namespace命名规则 : 包名+类名

MyBatis 的真正强大在于它的映射语句,这是它的魔力所在。由于它的异常强大,映射器的 XML 文件就显得相对简单。如果拿它跟具有相同功能的 JDBC 代码进行对比,你会立即发现省掉了将近 95% 的代码。MyBatis 为聚焦于 SQL 而构建,以尽可能地为你减少麻烦。

Properties优化:

该节点表明可以使用一个单独的properties文件存储属性。然后使用        导入该文件

typeAliases优化:

类型别名是为 Java 类型设置一个短的名字。它只和 XML 配置有关,存在的意义仅在于用来减少类完全限定名的冗余。


<typeAliases>
   <typeAlias type="com.kuang.pojo.User" alias="User"/>
typeAliases>

当这样配置时,User可以用在任何使用com.kuang.pojo.User的地方。

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:

<typeAliases>
   <package name="com.kuang.pojo"/>
typeAliases>

每一个在包 com.kuang.pojo 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。

若有注解,则别名为其注解值。见下面的例子:

@Alias("user")
public class User {
  ...
}

其它配置:

  • 设置(settings)相关 => 查看帮助文档

    • 懒加载

    • 日志实现

    • 缓存开启关闭

  • 一个配置完整的 settings 元素的示例如下:

    <settings>
     <setting name="cacheEnabled" value="true"/>
     <setting name="lazyLoadingEnabled" value="true"/>
     <setting name="multipleResultSetsEnabled" value="true"/>
     <setting name="useColumnLabel" value="true"/>
     <setting name="useGeneratedKeys" value="false"/>
     <setting name="autoMappingBehavior" value="PARTIAL"/>
     <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
     <setting name="defaultExecutorType" value="SIMPLE"/>
     <setting name="defaultStatementTimeout" value="25"/>
     <setting name="defaultFetchSize" value="100"/>
     <setting name="safeRowBoundsEnabled" value="false"/>
     <setting name="mapUnderscoreToCamelCase" value="false"/>
     <setting name="localCacheScope" value="SESSION"/>
     <setting name="jdbcTypeForNull" value="OTHER"/>
     <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
    settings>

类型处理器

  • 无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。

  • 你可以重写类型处理器或创建你自己的类型处理器来处理不支持的或非标准的类型。【了解即可】

对象工厂

  • MyBatis 每次创建结果对象的新实例时,它都会使用一个对象工厂(ObjectFactory)实例来完成。

  • 默认的对象工厂需要做的仅仅是实例化目标类,要么通过默认构造方法,要么在参数映射存在的时候通过有参构造方法来实例化。

  • 如果想覆盖对象工厂的默认行为,则可以通过创建自己的对象工厂来实现。【了解即可】

作用域(Scope)和生命周期

理解我们目前已经讨论过的不同作用域和生命周期类是至关重要的,因为错误的使用会导致非常严重的并发问题。

我们可以先画一个流程图,分析一下Mybatis的执行过程!

 作用域理解:

SQLSessionFactoryBuilder对象负责生产SQLSession对象,一旦对象生成完毕,就失去作用,因此它只作用于创建SqlSession对象,在该对象创建完毕后应该销毁,所以最佳作用域是方法作用域(也就是局部方法变量)

 SqlSessionFactory 对象负责创建SqlSession对象,可以被认定为是一个数据库连接池,因为mybatis的本质就是Java操作数据库,因此该对象应该存在于整个Mybatis运行的生命周期内,直至不再使用mybatis应用,所以该对象的作用域等同于mybatis的应用周期。

  注意:

  • 由于 SqlSessionFactory 是一个对数据库的连接池,所以它占据着数据库的连接资源。如果创建多个 SqlSessionFactory,那么就存在多个数据库连接池,这样不利于对数据库资源的控制,也会导致数据库连接资源被消耗光,出现系统宕机等情况,所以尽量避免发生这样的情况。

  • 在一般的应用中我们往往希望SqlSession对象是一个单例,让它在应用中被共享。

因此该对象的最佳作用域应该是应用作用域。

 

SqlSession对象:如果说SqlSessionFactory是一个数据库连接池,那么SqlSession就是一个数据库连接对象(connection),你可以在一个事务里面执行多条 SQL,然后通过它的 commit、rollback 等方法,提交或者回滚事务。所以它应该存活在一个业务请求中,处理完整个请求后,应该关闭这条连接,让它归还给 SqlSessionFactory,否则数据库资源就很快被耗费精光,系统就会瘫痪,所以用 try...catch...finally... 语句来保证其正确关闭。

因此该对象的最佳作用域应该是请求或者方法作用域。

关于日志的处理:

Mybatis内置的日志工厂提供日志功能,具体的日志实现有以下几种工具:

  • SLF4J

  • Apache Commons Logging

  • Log4j 2

  • Log4j

  • JDK logging

具体选择哪个日志实现工具由MyBatis的内置日志工厂确定。它会使用最先找到的(按上文列举的顺序查找)。如果一个都未找到,日志功能就会被禁用。

标准日志实现

指定 MyBatis 应该使用哪个日志记录实现。如果此设置不存在,则会自动发现日志记录实现

<settings>
       <setting name="logImpl" value="STDOUT_LOGGING"/>
settings>

log4j

1、导入log4j的包
<dependency>
   <groupId>log4jgroupId>
   <artifactId>log4jartifactId>
   <version>1.2.17version>
dependency>

2、配置文件编写

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

3、setting设置日志实现

<settings>
   <setting name="logImpl" value="LOG4J"/>
settings>

4、在程序中使用Log4j进行输出!

//注意导包:org.apache.log4j.Logger
static Logger logger = Logger.getLogger(MyTest.class);

@Test
public void selectUser() {
   logger.info("info:进入selectUser方法");
   logger.debug("debug:进入selectUser方法");
   logger.error("error: 进入selectUser方法");
   SqlSession session = MybatisUtils.getSession();
   UserMapper mapper = session.getMapper(UserMapper.class);
   List users = mapper.selectUser();
   for (User user: users){
       System.out.println(user);
  }
   session.close();
}

关于mybatis中的多对一的解决(使用association标签):
1、子查询

<?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="com.kuang.mapper.StudentMapper">

   
   <select id="getStudents" resultMap="StudentTeacher">
    select * from student
   select>
   <resultMap id="StudentTeacher" type="Student">
       
       <association property="teacher"  column="tid" javaType="Teacher" select="getTeacher"/>
   resultMap>
   
   <select id="getTeacher" resultType="teacher">
      select * from teacher where id = #{id}
   select>

mapper>

注意点(可以传多个值给下一个查询,类似子查询):

<resultMap id="StudentTeacher" type="Student">
   
   <association property="teacher"  column="{id=tid,name=tid}" javaType="Teacher" select="getTeacher"/>
resultMap>

<select id="getTeacher" resultType="teacher">
  select * from teacher where id = #{id} and name = #{name}
select>

2、嵌套查询


<select id="getStudents2" resultMap="StudentTeacher2" >
  select s.id sid, s.name sname , t.name tname
  from student s,teacher t
  where s.tid = t.id
select>

<resultMap id="StudentTeacher2" type="Student">
   <id property="id" column="sid"/>
   <result property="name" column="sname"/>
   
   <association property="teacher" javaType="Teacher">
       <result property="name" column="tname"/>
   association>
resultMap>

关于多对一的解决方法():

<mapper namespace="com.kuang.mapper.TeacherMapper">

   
   <select id="getTeacher" resultMap="TeacherStudent">
      select s.id sid, s.name sname , t.name tname, t.id tid
      from student s,teacher t
      where s.tid = t.id and t.id=#{id}
   select>

   <resultMap id="TeacherStudent" type="Teacher">
       <result  property="name" column="tname"/>
       <collection property="students" ofType="Student">
           <result property="id" column="sid" />
           <result property="name" column="sname" />
           <result property="tid" column="tid" />
       collection>
   resultMap>
mapper>

第二种解决方法(类似子查询的):

<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id = #{id}
select>
<resultMap id="TeacherStudent2" type="Teacher">
   
   <collection property="students" javaType="ArrayList" ofType="Student" column="id" select="getStudentByTeacherId"/>
resultMap>
<select id="getStudentByTeacherId" resultType="Student">
  select * from student where tid = #{id}
select>
Mybatis中的动态Sql:
掌握以下标签的使用
  • if
  • where
    <select id="queryBlogIf" parameterType="map" resultType="blog">
      select * from blog
       <where>
           <if test="title != null">
              title = #{title}
           if>
           <if test="author != null">
              and author = #{author}
           if>
       where>
    select>

    这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。


  • choose(when, otherwise)
    <select id="queryBlogChoose" parameterType="map" resultType="blog">
      select * from blog
       <where>
           <choose>
               <when test="title != null">
                    title = #{title}
               when>
               <when test="author != null">
                  and author = #{author}
               when>
               <otherwise>
                  and views = #{views}
               otherwise>
           choose>
       where>
    select>
  • sql标签

    <sql id="if-title-author">
       <if test="title != null">
          title = #{title}
       if>
       <if test="author != null">
          and author = #{author}
       if>
    sql>

    引用sql片段:

    <select id="queryBlogIf" parameterType="map" resultType="blog">
      select * from blog
       <where>
           
           <include refid="if-title-author">include>
           
       where>
  • Foreach标签
    <select id="queryBlogForeach" parameterType="map" resultType="blog">
      select * from blog
       <where>
           
           <foreach collection="ids"  item="id" open="and (" close=")" separator="or">
              id=#{id}
           foreach>
       where>
    select>
  • Set
    
    <update id="updateBlog" parameterType="map">
      update blog
         <set>
             <if test="title != null">
                title = #{title},
             if>
             <if test="author != null">
                author = #{author}
             if>
         set>
      where id = #{id};
    update>

Mybatis中的缓存机制:

mybatis 中的缓存分为一级缓存跟二级缓存

  • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)

  • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。

  • 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存

一级缓存也叫本地缓存:

  • 与数据库同一次会话期间查询到的数据会放在本地缓存中。

  • 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库;

一级缓存是SqlSession级别的缓存,是一直开启的,我们关闭不了它;

一级缓存失效情况:没有使用到当前的一级缓存,效果就是,还需要再向数据库中发起一次查询请求!

1、sqlSession不同

2、sqlSession相同,查询条件不同

3、sqlSession相同,两次查询之间执行了增删改操作!

4、sqlSession相同,手动清除一级缓存(clearCache()方法)

二级缓存:

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存

  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;

  • 工作机制

    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;

    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;

    • 新的会话查询信息,就可以从二级缓存中获取内容;

    • 不同的mapper查出的数据会放在自己对应的缓存(map)中;

使用步骤:

  1. 开启全局缓存 【mybatis-config.xml】
    <setting name="cacheEnabled" value="true"/>
  2. 去每个mapper.xml中配置使用二级缓存,这个配置非常简单;【xxxMapper.xml】
    <cache/>
    
    官方示例=====>查看官方文档
    <cache
     eviction="FIFO"
     flushInterval="60000"
     size="512"
     readOnly="true"/>
    这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
  3. 开始测试。
    @Test
    public void testQueryUserById(){
       SqlSession session = MybatisUtils.getSession();
       SqlSession session2 = MybatisUtils.getSession();
    
       UserMapper mapper = session.getMapper(UserMapper.class);
       UserMapper mapper2 = session2.getMapper(UserMapper.class);
    
       User user = mapper.queryUserById(1);
       System.out.println(user);
       session.close();
    
       User user2 = mapper2.queryUserById(1);
       System.out.println(user2);
       System.out.println(user==user2);
    
       session2.close();
    }

 结论:

  • 只要开启了二级缓存,我们在同一个Mapper中的查询,可以在二级缓存中拿到数据

  • 查出的数据都会被默认先放在一级缓存中

  • 只有会话提交或者关闭以后,一级缓存中的数据才会转到二级缓存中

    缓存原理图: