MyBatis文档解读(1)

地址

  • 项目网址
  • Mybatis项目在git hub上托管
  • https://github.com/mybatis/mybatis-3
  • 进入后在页面的最下方README.md的文档展示里,点开在Essentials 下的ownload Latest可以下载到最新的Mybaitis
    • 或者用项目菜单的releases按钮去找最新发布的版本或以前的版本。
      • 在版本号下的Enhancements和Bug fixes,是介绍本版本增强和Bug修复。
  • 文档地址

从官方文档来复习我们的工具,什么是Mybatis

  • MyBatis is a first class persistence framework with support for custom SQL, stored procedures
    and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of
    parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration
    and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.
  • MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

解读官方文档

Getting started
Installation(安装)
  • IDE:eclipse
  • 大家都已经习惯了使用Maven来构建项目,文档首先给出的是另一种安装方案,把自己所需版本的Mybaitis下载后,在其中找到jar包mybatis-x.x.x.jar,比如mybatis-3.5.3.jar,在项目下新建一个lib文件夹,把jar包拷贝进去,然后对jar包右键点击Build Path再点击Add to Build Path,如果在Java Resourse下Libraries下出现了Reference Libraries,其中有刚才添加的jar包,说明安装成功。
    • 基本的程序编写与测试需要数据库驱动,还需要导入mysql-connector-java-x.x.x.jar
  • Remove(删除)
    • 右键点击Reference Libraries的jar包,点击Build Path 再点击Remove from Build Path
  • 接着官方文档又给出了我们常用的Maven导包方式
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>x.x.x</version>
    </dependency>
Building SqlSessionFactory from XML(从 XML 中构建 SqlSessionFactory)
  • Every MyBatis application centers around an instance of SqlSessionFactory. A SqlSessionFactory
    instance can be acquired by using the SqlSessionFactoryBuilder. SqlSessionFactoryBuilder can build
    a SqlSessionFactory instance from an XML configuration file, or from a custom prepared instance of
    the Configuration class.
    Building a SqlSessionFactory instance from an XML file is very simple. It is recommended that you
    use a classpath resource for this configuration, but you could use any InputStream instance, including
    one created from a literal file path or a file:// URL. MyBatis includes a utility class, called Resources,
    that contains a number of methods that make it simpler to load resources from the classpath and other
    locations.
  • 每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration 的实例构建出 SqlSessionFactory 的实例。
    从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。 可以使用任意的输入流(InputStream)实例,包括字符串形式的文件路径或者 file:// 的 URL 形式的文件路径来配置。MyBatis 包含一个名叫 Resources的工具类,它包含一些实用方法,可使从 classpath 或其他位置加载资源文件更加容易。
    • 概括的说,我们用的Mybatis有一个关键的类SqlSessionFactory,我们通过SqlSessionFactory所获取到的sqlSession实例来映射sql语句,即便是与spring整合,底层依然是调用SqlSession的方法。SqlSessionFactory实例则可以通过XML来构建,在主方法或junit的测试类写如下代码,来获得从XML中构建SqlSessionFactory。
          //获得全局配置文件
          String resource = "mybatis-config.xml";
          InputStream inputStream = 
      	Resources.getResourceAsStream(resource);
          SqlSessionFactory sqlSessionFactory =
      	        new SqlSessionFactoryBuilder().build(inputStream);
      	//2、获取sqlSession实例 能直接执行已经映射的sql语句
          try(SqlSession openSession = sqlSessionFactory.openSession();){
      	Employee employee = openSession.selectOne("yourId",1);
  • 全局配置文件的配置(官方示例)
    • 该示例的语法适用于使用标签。

      <?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="${driver}"/>
                  <property name="url" value="${url}"/>
                  <property name="username" value="${username}"/>
                  <property name="password" value="${password}"/>
              </dataSource>
              </environment>
      </environments>
      <mappers>
      <mapper resource="org/mybatis/example/BlogMapper.xml"/>
      </mappers>
      </configuration>
      
    • 如果不使用标签,则需要修改数据源的配置方式,可以这样写:

      <?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.cj.jdbc.Driver"/>
                  <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Chongqing"/>
                  <property name="username" value="root"/>
                  <property name="password" value=""/>
              </dataSource>
              </environment>
      </environments>
      <mappers>
      <mapper resource="org/mybatis/example/BlogMapper.xml"/>
      </mappers>
      </configuration>
      
  • 稍后文档会给出映射文件的写法,写好的映射文件一定要注册到全局配置文件中,使用标签注册。
    • 在eclipse的Maven项目下用引入定义sql语句的XML文件时,把文件放在resources下。
Acquiring a SqlSession from SqlSessionFactory 从SqlSessionFactory 中获取 SqlSession
  • 前面已经提到了,SqlSessionFactory之所以重要,是因为我们通过它获取SqlSession,SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。可以通过 SqlSession 实例来直接执行已映射的 SQL 语句,官方文档如下。

    • Now that you have a SqlSessionFactory, as the name suggests, you can acquire an instance of
      SqlSession. The SqlSession contains absolutely every method needed to execute SQL commands
      against the database. You can execute mapped SQL statements directly against the SqlSession
      instance.
    • 既然有了 SqlSessionFactory,顾名思义,我们就可以从中获得 SqlSession 的实例了。SqlSession 完全包含了面向数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句。
  • 官方文档首先给出的方法是比较原始的方法,通过调用SqlSession实例的selectOne()方法传入id来执行已经映射的sql语句

    • 方法里的id值是映射文件里命名空间的值加上要映射的sql语句的id的值,在这种使用方式下,虽然用 . 隔开很像地址,但可以不是真实地址。
    • 如下代码所示,在sql映射文件里命名空间的值是org.mybatis.example.BlogMapper,sql语句的id是selectBlog,在代码里就写成"org.mybatis.example.BlogMapper.selectBlog"来映射到所需的sql语句。
      //需要关闭资源
      try (SqlSession session = sqlSessionFactory.openSession()) {
          //org.mybatis.example.BlogMapper是映射文件中命名空间的值selectBlog是id,
          //要和要映射的sql语句的id保持一致。
          Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
      }
      
    • selectOne();
      • Parameters 参数:
        • statement Unique identifier matching the statement to use.
        • 解释:selectOne方法的第一个参数是sql语句的唯一标识符
        • parameter A parameter object to pass to the statement.
        • 解释:第二个参数是执行sql语句要执行的参数。
  • 接下来官方文档给出了第二种我们现在常用的方法,使用接口。这种方式的优点是可以正确描述每个语句的参数和返回值,可以执行更清晰和类型安全的代码,也不用担心易错的字符串字面值以及强制类型转换,是推荐的方法,代码如下。

    //需要关闭资源
    try (SqlSession session = sqlSessionFactory.openSession()) {
        BlogMapper mapper = session.getMapper(BlogMapper.class);
        Blog blog = mapper.selectBlog(101);
    }
    
Exploring Mapped SQL Statements 已经映射的sql语句
  • 前面讲过,无论使用哪种方法,都需要已经映射的sql语句,这些语句执行后返回的结果会与对象进行映射,官方文档中给出的示例如下:
<?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="org.mybatis.example.BlogMapper">
 <select id="selectBlog" resultType="Blog">
 select * from Blog where id = #{id}
 </select>
</mapper>
  • 标签、属性和语法介绍

    • namespace
      • 前面已经提及,在较早的用法里, namespace是为了构成id,其值可以不是真实的地址。
      • 而如果使用接口进行映射,namespace的值必须是包含接口文件的真实地址。
    • resultType
      • 返回值类型,写用于封装的类
    • #{id}
      • 从传递过来的参数中取出id值,
  • bean类的属性命名规则

    • 数据库字段名和bean类的属性名要一致。
Configuration XML (全局配置文件的编写)
properties
  • 可以使用properties标签来引入外部配置文件的内容
  • 如果不使用的话也可以在标签里直接写
    • resource:引入类路径下的资源
    • url:引入网络路径或者磁盘路径下的资源
  • 属性前面可以加上前缀,通过前缀名加属性名就可以获得。
mybatis.driver=com.mysql.jdbc.Driver
mybatis.url=jdbc:mysql://localhost:3306/mybatis
mybatis.username=root
mybatis.password=root
settings
  • 包含了很多的设置项,都能影响mybatis的运行行为
  • 内含setting:用来设置每一个设置项
    • name: 设置项名
    • value: 设置项取值
设置名,在标签里是name的值描述可以设置的值默认值
cacheEnabled全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存。true /falsetrue
mapUnderscoreToCamelCase是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。true /falseFalse
  • mapUnderscoreToCamelCase
    • 映射下划线变为驼峰命名,这个是用来告诉MyBatis是否开启驼峰命名策略,如果开启的话可以使数据库名A_COLUMN映射到javaBean类的用驼峰命名的属性。
  • 一个配置完整的 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>
别名处理器 typeAliases
  • A type alias is simply a shorter name for a Java type. It’s only relevant to the XML configuration and simply exists to reduce redundant typing of fully qualified classnames.

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

  • 概括的说,typeAliases的用法是给java类起一个短一点的别名,在全库配置文件中引用全类名的地方就可以写别名了。

    • typeAlias标签。其下有typeAlias标签,为某一个类型起别名。

      • typeAlias的属性type:指定要起别名的类型全类名。默认别名就是类名小写。
      • typeAlias的属性alias:指定新的别名。
      <typeAliases>
          <typeAlias alias="Author" type="domain.blog.Author"/>
          <typeAlias alias="Blog" type="domain.blog.Blog"/>
          <typeAlias alias="Comment" type="domain.blog.Comment"/>
          <typeAlias alias="Post" type="domain.blog.Post"/>
          <typeAlias alias="Section" type="domain.blog.Section"/>
          <typeAlias alias="Tag" type="domain.blog.Tag"/>
      </typeAliases>
      
    • package标签。其下还有另一种配置方式,批量起别名,使用package标签。
      为某个包下的所有类批量起别名。

      • 属性name:指定包名(为当前包及下面所有的后代的每一个类都起一个默认别名,是类名小写)。
      <typeAliases>
      <package name="domain.blog"/>
      </typeAliases>
      
      • 若有注解,则别名为其注解值。
      @Alias("author")
      public class Author {
          ...
      }
      
typeHandles 类型处理器
  • Whenever MyBatis sets a parameter on a PreparedStatement or retrieves a value from a ResultSet, a
    TypeHandler is used to retrieve the value in a means appropriate to the Java type. The following table
    describes the default TypeHandlers.
    NOTE Since version 3.4.5, MyBatis supports JSR-310 (Date and Time API) by default.
  • 无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。下表描述了一些默认的类型处理器。
    从 3.4.5 开始,MyBatis 默认支持 JSR-310(日期和时间 API) 。
  • 概括的说typeHandles架起了java类型和数据库类型一一映射的桥梁。在做数据库和java类型映射的时候,MyBatis就是用的typeHandles。
    • JSR310,一个标准,在JDK1.8之后出现的,添加了更丰富的日期类型库。MyBatis为这些日期类型写了新的类型处理器。
    • 从 3.4.5 开始,MyBatis 默认支持 JSR-310(日期和时间 API) 。
plugins 插件
  • MyBatis allows you to intercept calls to at certain points within the execution of a mapped statement.
    By default, MyBatis allows plug-ins to intercept method calls of:
  • MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:
Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
ParameterHandler (getParameterObject, setParameters)
ResultSetHandler (handleResultSets, handleOutputParameters)
StatementHandler (prepare, parameterize, batch, update, query)
  • 上面的示例是按对象划分的。这四个对象,每个都有不同的作用
      1. Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
      • 这是执行器,括号后面是这个对象拥有的方法,插件可以拦截到这些方法。
      • 利用插件机制可以在MyBatis的Executor对象执行真正的增删改之前改变MyBatis的默认行为达到自定义的效果。
      1. ParameterHandler (getParameterObject, setParameters)
      • 参数处理器
      1. ResultSetHandler (handleResultSets, handleOutputParameters)
      • 结果集处理器
      • 作用是把查出的数据拿到结果集,并封装成JavaBean对象
      1. StatementHandler (prepare, parameterize, batch, update, query)
      • sql语句的处理器
environments 环境配置
  • MyBatis can be configured with multiple environments. This helps you to apply your SQL Maps to
    multiple databases for any number of reasons. For example, you might have a different configuration
    for your Development, Test and Production environments. Or, you may have multiple production
    databases that share the same schema, and you’d like to use the same SQL maps for both. There are
    many use cases.

  • MyBatis 可以配置成适应多种环境,这种机制有助于将 SQL 映射应用于多种数据库之中, 现实情况下有多种理由需要这么做。例如,开发、测试和生产环境需要有不同的配置;或者想在具有相同 Schema 的多个生产数据库中 使用相同的 SQL 映射。有许多类似的使用场景。

  • One important thing to remember though: While you can configure multiple environments, you can only choose ONE per SqlSessionFactory instance.

  • 注意:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

  • environments 介绍

    • default 指定使用某种环境。可以达到快速切换环境的目的。
    • 其下有 environment 标签,配置一个具体的环境信息。
  • environments下的environment 标签

    • environment标签下必须配置transactionManager,事务管理器。

      • 其中有属性type,事务管理器的类型。
      • 在 MyBatis 中有两种类型的事务管理器 JDBC和MANAGED。
        • JDBC类型。这个配置就是直接使用了 JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务作用域。
        • MANAGED类型。这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。 默认情况下它会关闭连接,然而一些容器并不希望这样,因此需要将 closeConnection 属性设置为 false 来阻止它默认的关闭行为。
        • 也可以使用自定义事务管理器,要实现TransactionFactory接口。
        • 如果你正在使用 Spring + MyBatis,则没有必要配置事务管理器, 因为 Spring 模块会使用自带的管理器来覆盖前面的配置。
    • environment标签必须配置dataSource标签。

      • dataSource标签的type属性值是数据源类型。
      • 有UNPOOLED、POOLED、JNDI三种。
        • UNPOOLED,不使用连接池的技术。每一次增删改查都会从数据库中那拿一次新的连接,而不是使用连接池。
        • POOLED,使用连接池技术。
        • JNDI,这个数据源的实现是为了能在如 EJB 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 上下文的引用。
      • 也可以使用自定义数据源:实现DataSourceFactory接口,
        利用接口中的getDataSource()方法返回我们需要的数据源。
    • 标签还有一个属性id,代表当前环境的唯一标识。

      • 属性id代表当前环境的唯一标识。当测试和开发环境不同时,开发人员用本地的环境进行开发调试工作,而测试人员用专门的测试数据库,这时就可以配置两种环境(写写两个environment标签),一个测试环境,一个开发环境。测事人员把项目拿到以后用environments标签里的default属性指定id值来配置来快速切换到不同的环境。
databaseIdProvider 数据库厂商标识
  • MyBatis is able to execute different statements depending on your database vendor. The multi-db
    vendor support is based on the mapped statements databaseId attribute. MyBatis will load all
    statements with no databaseId attribute or with a databaseId that matches the current one. In
    case the same statement is found with and without the databaseId the latter will be discarded. To
    enable the multi vendor support add a databaseIdProvider to mybatis-config.

  • MyBatis 可以根据不同的数据库厂商执行不同的语句,这种多厂商的支持是基于映射语句中的 databaseId 属性。 MyBatis 会加载不带 databaseId 属性和带有匹配当前数据库 databaseId 属性的所有语句。 如果同时找到带有 databaseId 和不带 databaseId 的相同语句,则后者会被舍弃。

  • 概括的说,这个标签相当于MyBatis在一致性的支持。需要告诉MyBatis要执行的sql语句是哪个数据库厂商下的。MyBatis就会动态的根据数据库厂商标识来发送不同的sql语句。

    • 为支持多厂商特性只要像下面这样在 mybatis-config.xml 文件中加入 databaseIdProvider 即可:
      <databaseIdProvider type="DB_VENDOR" />
      
    • type="DB_VENDOR"是固定写法,作用是得到数据库厂商标识,写好后MyBatis就能根据数据库厂商标识来执行不同的sql语句。
      • 数据库厂商标识是驱动自带的
    • 为不同的数据库厂商起别名
    <databaseIdProvider type="DB_VENDOR">
    <property name="SQL Server" value="sqlserver"/>
    <property name="DB2" value="db2"/>
    <property name="Oracle" value="oracle" />
    </databaseIdProvider>
    
    • 然后在定义已映射的sql语句里的XML文件里找到定义语句的标签,配置databaseId属性。
      • 同一个id可以配置多个语句,但要求同一id下定义的已映射的sql语句各属于不同的数据库。MyBatis在识别时会根据设置的环境只识别环境匹配的sql语句。
      • 如果在同一个id下定义了不同数据库的已映射的sql语句,用environments标签切换数据库后,MyBatis会自动寻找并执行对应的sql语句。
     <select id="getEmpById" resultType="cn.blue.bean.Employee"
        databaseId="msq">
    
mappers 映射器
  • Now that the behavior of MyBatis is configured with the above configuration elements, we’re ready
    to define our mapped SQL statements. But first, we need to tell MyBatis where to find them. Java
    doesn’t really provide any good means of auto-discovery in this regard, so the best way to do it
    is to simply tell MyBatis where to find the mapping files. You can use classpath relative resource
    references, fully qualified url references (including file:/// URLs), class names or package names.
  • 既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要定义 SQL 映射语句了。 但是首先我们需要告诉 MyBatis 到哪里去找到这些语句。 Java 在自动查找这方面没有提供一个很好的方法,所以最佳的方式是告诉 MyBatis 到哪里去找映射文件。 你可以使用相对于类路径的资源引用, 或完全限定资源定位符(包括 file:/// 的 URL),或类名和包名等。
    • 概括的说,就是将定义已映射的sql语句的文件注册到全局配置中。
    • 在mappers下有mapper标签,执行具体的注册。
      • resource:引用类路径下的映射文件。
      • url:引用网路路径或者路径下的sql映射文件。
      • class:引用接口
        • 如果使用class属性,class的值不再是定义已映射sql语句的XML文件,而是关联的接口。定义已映射的sql语句的XMl文件必须和接口同名,并且放在与接口同一目录下。
        • 也可以没有定义已映射的sql语句的XML文件,而是用注解定义sql语句。
          • 基于注解使用class属性,是常用的方式。
          • 使用@Select()注解。
        • 批量注册
          • 定义已映射的sql语句的XMl文件必须和关联的接口同名,并且放在与接口该目录下。
          • 用注解定义sql语句的接口也要放在该目录下。
标签在全局文件中应该有的顺序
    1. properties
    1. settings
    1. typeAliases
    1. typeHandlers
    1. objectFactory
    1. objectWrapperFactory
    1. reflectorFactory
    1. plugins
    1. environments
    1. databaseldProvider
    1. mapppers
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
入门 安装 要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于 classpath 中即可。 如果使用 Maven 来构建项目,则需将下面的 dependency 代码置于 pom.xml 文件中: <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>x.x.x</version> </dependency>从 XML 中构建 SqlSessionFactory 每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为中心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先定制的 Configuration 的实例构建出 SqlSessionFactory 的实例。 从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。但是也可以使用任意的输入流(InputStream)实例,包括字符串形式的文件路径或者 file:// 的 URL 形式的文件路径来配置。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,可使从 classpath 或其他位置加载资源文件更加容易。 String resource = "org/mybatis/example/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);XML 配置文件(configuration XML)中包含了对 MyBatis 系统的核心设置,包含获取数据库连接实例的数据源(DataSource)和决定事务作用域和控制方式的事务管理器(TransactionManager)。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="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>当然,还有很多可以在XML 文件中进行配置,上面的示例指出的则是最关键的部分。要注意 XML 头部的声明,用来验证 XML 文档正确性。environment 元素体中包含了事务管理和连接池的配置。mappers 元素则是包含一组 mapper 映射器(这些 mapper 的 XML 文件包含了 SQL 代码和映射定义信息)。 不使用 XML 构建 SqlSessionFactory 如果你更愿意直接从 Java 程序而不是 XML 文件中创建 configuration,或者创建你自己的 configuration 构建器,MyBatis 也提供了完整的配置类,提供所有和 XML 文件相同功能的配置项。 .....................................
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值