Mybatis[2] - 配置文件讲解

前言

    上一篇文章介绍了入门级别的MyBatis的HelloWorld程序(http://blog.csdn.net/program_red/article/details/562901
57),本文主要讲述mybatis的一些配置文件的使用姿势和用途,主要涉及到映射文件、配置文件;

配置文件

每一个应用只有一个启动配置的配置文件一般存放在类根路径下(mybatis-config.xml)也可以存放在其他位置。其作用是管理数据源配置(连接、事务等)、映射关系管理。
官方描述:[http://www.mybatis.org/mybatis3/zh/configuration.html]

properties 标签

标签属性元素
包含url和resource元素
url: 远程加载,基于协议加载,可以是file,http,https等;
resource: 类加载,默认就是类根路径
但是需要特别注意一点就是:url和resource属性,同时只能选择一种,不然会报错:(摘自源码)
if (resource != null && url != null) {
        throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
      }
示例

[1] url加载测试
mybatis-config-properties-url.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>

    <!-- 属性配置标签
        1. 可以加载properties配置文件(默认加载类根路径),标签属性元素:
            url: 一般用于远程加载,通过访问协议获取
            resource: 加载类路径下的配置文件
       2.但是url和resource只能同时存在一个
    -->
    <properties url="file:///Users/wangzhiping/idea-workspace/csdn_mybatis/hello-props/src/conf/jdbc.properties">
    </properties>
</configuration>

单元测试:

 /**
   * 配置文件:mybatis-config-properties-url.xml
   */
@Test
public void testUrlProperties(){
        try {
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config-properties-url.xml"));
            Configuration configuration = factory.getConfiguration();
            Properties properties = configuration.getVariables();
            Assert.assertEquals(properties.getProperty("db.username"), "root");
            Assert.assertEquals(properties.getProperty("db.password"), "root");
            Assert.assertEquals(properties.getProperty("db.driver"), "com.mysql.cj.jdbc.Driver");
            Assert.assertEquals(properties.getProperty("db.url"), "jdbc:mysql://localhost:3306/csdn?charset=utf8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

[2] resource加载
mybatis-config-properties-resource.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>

    <!-- 属性配置标签
        1. 可以加载properties配置文件(默认加载类根路径),标签属性元素:
            url: 一般用于远程加载,通过访问协议获取
            resource: 加载类路径下的配置文件
       2.但是url和resource只能同时存在一个
    -->
    <properties resource="jdbc.properties">
    </properties>
</configuration>

单元测试:

 /**
     * 配置文件:mybatis-config-properties-resource.xml
     */
    @Test
    public void testResourceProperties(){
        try {
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config-properties-resource.xml"));
            Configuration configuration = factory.getConfiguration();
            Properties properties = configuration.getVariables();
            Assert.assertEquals(properties.getProperty("db.username"), "root");
            Assert.assertEquals(properties.getProperty("db.password"), "root");
            Assert.assertEquals(properties.getProperty("db.driver"), "com.mysql.cj.jdbc.Driver");
            Assert.assertEquals(properties.getProperty("db.url"), "jdbc:mysql://localhost:3306/csdn?charset=utf8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
子标签
除了可以通过上述的url/resource来加载properties配置文件以外,还可以进行子标签设置属性值,如果resource/url也加载了,同时子标签也设置了同一个属性的值,会前者覆盖后者,因为mybatis是先加载property子标签内容,后加载resource/url标签;

范例:
mybatis-config-properties-property.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>

    <!-- 属性配置标签
        1. 可以加载properties配置文件(默认加载类根路径),标签属性元素:
            url: 一般用于远程加载,通过访问协议获取
            resource: 加载类路径下的配置文件
       2.但是url和resource只能同时存在一个
    -->
    <properties resource="jdbc.properties">
        <property name="db.test01" value="test01" />
        <property name="db.test02" value="test02" />
        <property name="db.username" value="root1" />
        <property name="db.password" value="root2" />
    </properties>


</configuration>

单元测试:

 /**
     * 配置文件:mybatis-config-properties-property.xml
     * property标签,设置的也会加载到配置变量中,供后续配置使用,会出现一种情况需要解决
     * 情况:
     * 如果resource/url加载的配置文件与property属性名重复了,是怎么取值的?
     */
    @Test
    public void testPropertiesProperty(){
        try {
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config-properties-property.xml"));
            Configuration configuration = factory.getConfiguration();
            Properties properties = configuration.getVariables();
            Assert.assertEquals(properties.getProperty("db.username"), "root");
            Assert.assertEquals(properties.getProperty("db.password"), "root");
            Assert.assertEquals(properties.getProperty("db.driver"), "com.mysql.cj.jdbc.Driver");
            Assert.assertEquals(properties.getProperty("db.url"), "jdbc:mysql://localhost:3306/csdn?charset=utf8");
            Assert.assertEquals(properties.getProperty("db.test01"), "test01");
            Assert.assertEquals(properties.getProperty("db.test02"), "test02");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 配置文件:mybatis-config-properties-property.xml
     * property标签,设置的也会加载到配置变量中,供后续配置使用,会出现一种情况需要解决
     * 情况:
     * 如果resource/url加载的配置文件与property属性名重复了,是怎么取值的?
     * 结果:
     * 1,mybatis先加载property子标签的属性值;
     * 2,然后在加载resource/url加载的属性值,这样就会导致resource/url加载配置文件覆盖标签<property></property>的重复属性值
     */
    @Test
    public void testResetPropertiesProperty(){
        try {
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config-properties-property.xml"));
            Configuration configuration = factory.getConfiguration();
            Properties properties = configuration.getVariables();

            // 如果resource/url加载的配置文件与property标签重复属性;
            // 那么属性值会按照property先加载,在加载resource/url的属性配置,后者覆盖前者
            Assert.assertEquals(properties.getProperty("db.username"), "root");
            Assert.assertEquals(properties.getProperty("db.password"), "root");

            Assert.assertEquals(properties.getProperty("db.driver"), "com.mysql.cj.jdbc.Driver");
            Assert.assertEquals(properties.getProperty("db.url"), "jdbc:mysql://localhost:3306/csdn?charset=utf8");

            // 这里是property标签没有的属性值,会按照property属性值设置
            Assert.assertEquals(properties.getProperty("db.test01"), "test01");
            Assert.assertEquals(properties.getProperty("db.test02"), "test02");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    属性操作在引用时,可以进行表达式处理,这里不做阐述,一个是比较简单,另一个实际生产使用并不多。

settings 标签

这个主要是mybatis系统配置参数的设置标签,通过设置一些参数,可以改变运行时的行为。

例如:

<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"/>
  <!-- 在DEBUG时,比较常用 -->
  <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

这里不做详细概述和范例模拟,可以参考:
http://www.mybatis.org/mybatis-3/zh/configuration.html#settings

typeAliases 标签

    顾名思义:类型别名标签,这个比较常用,主要有两个子标签
    1,<typeAlias>: 类型和别名1对1关联定义;
    2,<package>: 一般使用在pojo包结构下;
typeAlias 子标签
语法:<typeAlias type="具体类型" name="别名"></typeAlias>

示例:
mybatis-config-properties-typealiases.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>

    <!-- 属性配置标签
        1. 可以加载properties配置文件(默认加载类根路径),标签属性元素:
            url: 一般用于远程加载,通过访问协议获取
            resource: 加载类路径下的配置文件
       2.但是url和resource只能同时存在一个
    -->
    <properties resource="jdbc.properties"/>

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

    <environments default="test">
        <environment id="test">

            <transactionManager type="JDBC"></transactionManager>


            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}" />
                <property name="url" value="${db.url}" />
                <property name="username" value="${db.username}" />
                <property name="password" value="${db.password}" />
                <!-- 还可以做一些连接池的配置,这里不做展开 -->
            </dataSource>
        </environment>
    </environments>

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

</configuration>

User.xml

<?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.props.pojo.User">

    <!-- 没有别名设置的情况,类型必须是全限定名
    注意:resultType:返回类型,必须是全限定名,不然找不到类型
    -->
    <select id="findByIdAndNotTypeAlias" parameterType="int" resultType="com.props.pojo.User">
        SELECT * FROM user WHERE id=#{id}
    </select>

    <!-- 通过设置类别名来简化操作 -->
    <select id="findByIdAndTypeAlias" parameterType="int" resultType="User">
        SELECT * FROM user WHERE id=#{id}
    </select>

</mapper>

单元测试

package com.props;

import com.props.pojo.User;
import com.props.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

/**
 * 测试TypeAliases标签相关的配置
 * Created by wangzhiping on 17/2/24.
 */
public class TestTypeAliases {

    private MybatisUtils instance = MybatisUtils.getInstance("mybatis-config-properties-typealiases.xml");

    @Test
    public void testNotTypeAlias(){
        SqlSession session = instance.getSession();
        try{
            User user = session.selectOne("com.props.pojo.User.findByIdAndNotTypeAlias", 201);
            System.out.println(user);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            instance.closeSession(session);
        }
    }

    @Test
    public void testWithTypeAlias(){
        SqlSession session = instance.getSession();
        try{
            User user = session.selectOne("com.props.pojo.User.findByIdAndTypeAlias", 201);
            System.out.println(user);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            instance.closeSession(session);
        }
    }
}

概述

1、不使用别名时,我们就需要每次制定全限定名;
2、如果使用typeAlias定义了别名,那么可以使用别名;
3、当有N个类时,如果我们需要一个一个的定义,势必会导致配置文件很庞大,并且不利于维护;这个时候就可以考虑使用package子标签来完成。
package 子标签
<package name="bean加载类目录">

示例:
mybatis-config-properties-resource.xml

 <typeAliases>
        <!-- <typeAlias type="com.props.pojo.User" alias="User"/>-->
        <!-- 使用包时,指定了mybatis的bean加载目录 -->
        <package name="com.props.pojo" />
 </typeAliases>

单元测试:

@Test
public void testWithPackage(){
        SqlSession session = instance.getSession();
        try{
            User user = session.selectOne("com.props.pojo.User.findByIdAndTypeAlias", 201);
            System.out.println(user);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            instance.closeSession(session);
        }
}
如果现在还有一些其他需要别名的类,使用了package就不需要在重新标注了,带来了一些方面。
annotation 设置别名
其实,还可以通过annotation的方式进行注册别名,具体使用方式就是在相应的类上增加@Alias("别名"); 但是需要特别注意的是:annotation必须在使用package的情况下使用,如果此时使用了@Alias,那么必须以Alias的别名为主;

例如:
User.java

package com.props.pojo;


import org.apache.ibatis.type.Alias;

import java.io.Serializable;
import java.util.Date;

/**
 * Created by wangzhiping on 17/2/21.
 */
@Alias("UserAnnotation")
public class User implements Serializable{

    private Integer id;

    private String name;

    private Date createdAt;

    private Date updatedAt;

    public User() {
    }

    public User(Integer id, String name, Date createdAt, Date updatedAt) {
        this.id = id;
        this.name = name;
        this.createdAt = createdAt;
        this.updatedAt = updatedAt;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", createdAt=" + createdAt +
                ", updatedAt=" + updatedAt +
                '}';
    }
}

User.xml

<?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.props.pojo.User">

    <!-- 没有别名设置的情况,类型必须是全限定名
    注意:resultType:返回类型,必须是全限定名,不然找不到类型
    -->
    <select id="findByIdAndNotTypeAlias" parameterType="int" resultType="com.props.pojo.User">
        SELECT * FROM user WHERE id=#{id}
    </select>

    <!-- 通过设置类别名来简化操作;如果使用Annotation,那么User失效 -->
    <!--
    <select id="findByIdAndTypeAlias" parameterType="int" resultType="User">
        SELECT * FROM user WHERE id=#{id}
    </select>
    -->

    <!-- 通过设置类别名来简化操作 -->
    <select id="findByIdAndAnnotationAlias" parameterType="int" resultType="UserAnnotation">
        SELECT * FROM user WHERE id=#{id}
    </select>

</mapper>

mybatis-config-properties-annotation-aliases.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>

    <!-- 属性配置标签
        1. 可以加载properties配置文件(默认加载类根路径),标签属性元素:
            url: 一般用于远程加载,通过访问协议获取
            resource: 加载类路径下的配置文件
       2.但是url和resource只能同时存在一个
    -->
    <properties resource="jdbc.properties"/>

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

    <environments default="test">
        <environment id="test">

            <transactionManager type="JDBC"></transactionManager>

            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}" />
                <property name="url" value="${db.url}" />
                <property name="username" value="${db.username}" />
                <property name="password" value="${db.password}" />
                <!-- 还可以做一些连接池的配置,这里不做展开 -->
            </dataSource>
        </environment>
    </environments>

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

</configuration>

单元测试:

package com.props;

import com.props.pojo.User;
import com.props.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

/**
 * Created by wangzhiping on 17/2/24.
 */
public class TestAnnotationAlias {

    private MybatisUtils instance = MybatisUtils.getInstance("mybatis-config-properties-annotation-aliases.xml");

    @Test
    public void testNotTypeAlias(){
        SqlSession session = instance.getSession();
        try{
            User user = session.selectOne("com.props.pojo.User.findByIdAndNotTypeAlias", 201);
            System.out.println(user);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            instance.closeSession(session);
        }
    }


    @Test
    public void testWithPackageAndAnnotation(){
        SqlSession session = instance.getSession();
        try{
            User user = session.selectOne("com.props.pojo.User.findByIdAndAnnotationAlias", 201);
            System.out.println(user);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            instance.closeSession(session);
        }
    }

}
感觉Annotation没啥用处,基本不用,了解一下就好了,除非在重名时引入,不然没啥好处。
源码解析注册别名(摘自源码)
/**
 *    Copyright 2009-2015 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.type;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.io.ResolverUtil;
import org.apache.ibatis.io.Resources;

/**
 * @author Clinton Begin
 */
public class TypeAliasRegistry {

  private final Map<String, Class<?>> TYPE_ALIASES = new HashMap<String, Class<?>>();

  public TypeAliasRegistry() {
    registerAlias("string", String.class);

    registerAlias("byte", Byte.class);
    registerAlias("long", Long.class);
    registerAlias("short", Short.class);
    registerAlias("int", Integer.class);
    registerAlias("integer", Integer.class);
    registerAlias("double", Double.class);
    registerAlias("float", Float.class);
    registerAlias("boolean", Boolean.class);

    registerAlias("byte[]", Byte[].class);
    registerAlias("long[]", Long[].class);
    registerAlias("short[]", Short[].class);
    registerAlias("int[]", Integer[].class);
    registerAlias("integer[]", Integer[].class);
    registerAlias("double[]", Double[].class);
    registerAlias("float[]", Float[].class);
    registerAlias("boolean[]", Boolean[].class);

    registerAlias("_byte", byte.class);
    registerAlias("_long", long.class);
    registerAlias("_short", short.class);
    registerAlias("_int", int.class);
    registerAlias("_integer", int.class);
    registerAlias("_double", double.class);
    registerAlias("_float", float.class);
    registerAlias("_boolean", boolean.class);

    registerAlias("_byte[]", byte[].class);
    registerAlias("_long[]", long[].class);
    registerAlias("_short[]", short[].class);
    registerAlias("_int[]", int[].class);
    registerAlias("_integer[]", int[].class);
    registerAlias("_double[]", double[].class);
    registerAlias("_float[]", float[].class);
    registerAlias("_boolean[]", boolean[].class);

    registerAlias("date", Date.class);
    registerAlias("decimal", BigDecimal.class);
    registerAlias("bigdecimal", BigDecimal.class);
    registerAlias("biginteger", BigInteger.class);
    registerAlias("object", Object.class);

    registerAlias("date[]", Date[].class);
    registerAlias("decimal[]", BigDecimal[].class);
    registerAlias("bigdecimal[]", BigDecimal[].class);
    registerAlias("biginteger[]", BigInteger[].class);
    registerAlias("object[]", Object[].class);

    registerAlias("map", Map.class);
    registerAlias("hashmap", HashMap.class);
    registerAlias("list", List.class);
    registerAlias("arraylist", ArrayList.class);
    registerAlias("collection", Collection.class);
    registerAlias("iterator", Iterator.class);

    registerAlias("ResultSet", ResultSet.class);
  }

  @SuppressWarnings("unchecked")
  // throws class cast exception as well if types cannot be assigned
  public <T> Class<T> resolveAlias(String string) {
    try {
      if (string == null) {
        return null;
      }
      // issue #748
      String key = string.toLowerCase(Locale.ENGLISH);
      Class<T> value;
      if (TYPE_ALIASES.containsKey(key)) {
        value = (Class<T>) TYPE_ALIASES.get(key);
      } else {
        value = (Class<T>) Resources.classForName(string);
      }
      return value;
    } catch (ClassNotFoundException e) {
      throw new TypeException("Could not resolve type alias '" + string + "'.  Cause: " + e, e);
    }
  }

  public void registerAliases(String packageName){
    registerAliases(packageName, Object.class);
  }

  public void registerAliases(String packageName, Class<?> superType){
    ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
    resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
    Set<Class<? extends Class<?>>> typeSet = resolverUtil.getClasses();
    for(Class<?> type : typeSet){
      // Ignore inner classes and interfaces (including package-info.java)
      // Skip also inner classes. See issue #6
      if (!type.isAnonymousClass() && !type.isInterface() && !type.isMemberClass()) {
        registerAlias(type);
      }
    }
  }

  public void registerAlias(Class<?> type) {
    String alias = type.getSimpleName();
    Alias aliasAnnotation = type.getAnnotation(Alias.class);
    if (aliasAnnotation != null) {
      alias = aliasAnnotation.value();
    } 
    registerAlias(alias, type);
  }

  public void registerAlias(String alias, Class<?> value) {
    if (alias == null) {
      throw new TypeException("The parameter alias cannot be null");
    }
    // issue #748
    String key = alias.toLowerCase(Locale.ENGLISH);
    if (TYPE_ALIASES.containsKey(key) && TYPE_ALIASES.get(key) != null && !TYPE_ALIASES.get(key).equals(value)) {
      throw new TypeException("The alias '" + alias + "' is already mapped to the value '" + TYPE_ALIASES.get(key).getName() + "'.");
    }
    TYPE_ALIASES.put(key, value);
  }

  public void registerAlias(String alias, String value) {
    try {
      registerAlias(alias, Resources.classForName(value));
    } catch (ClassNotFoundException e) {
      throw new TypeException("Error registering type alias "+alias+" for "+value+". Cause: " + e, e);
    }
  }

  /**
   * @since 3.2.2
   */
  public Map<String, Class<?>> getTypeAliases() {
    return Collections.unmodifiableMap(TYPE_ALIASES);
  }

}

environments 标签

    数据环境标签,包含多个子标签 ,比如;aplha,beta,ppe,prod多套环境时,可以设置多套环境。
形式:
<environments default="多个环境选择指定环境ID">
    <environment id="环境ID">
    </environment>

    <environment id="">
    </environment>
    .
    .
    <environment id="">
    </environment>
</environments>
我们重点要讲述的内容是environment内部元素的使用方式;
transactionManager
    申明事务管理方式:
    1、JDBC:使用JDBC事务管理模式
    2、MANAGED:这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。 默认情况下它会关闭连接,然而一些容器并不希望这样,因此需要将 closeConnection 属性设置为 false 来阻止它默认的关闭行为。
<transactionManager type="MANAGED">
  <property name="closeConnection" value="false"/>
</transactionManager>
dataSource
    数据源配置,基本配置:
    1、driver:驱动
    2、url: 连接地址
    3、username: 用户名
    4、password: 密码
    5、defaultTransactionIsolationLevel:事务隔离级别;
    6、driver.encoding=UTF8:驱动编码格式
    主要包含了池化模式(POOLED)和非池化模式(UNPOOLD),如果是UNPOOLED那么只需要基本配置即可,如果是连接池模式(POOLED)那么还可以配置一些关于连接池的属性,例如:
1、poolMaximumActiveConnections – 在任意时间可以存在的活动(也就是正在使用)连接数量,默认值:10
2、poolMaximumIdleConnections – 任意时间可能存在的空闲连接数。
3、poolMaximumCheckoutTime – 在被强制返回之前,池中连接被检出(checked out)时间,默认值:20000 毫秒(即 20 秒)
4、poolTimeToWait – 这是一个底层设置,如果获取连接花费的相当长的时间,它会给连接池打印状态日志并重新尝试获取一个连接(避免在误配置的情况下一直安静的失败),默认值:20000 毫秒(即 20 秒)。
5、poolPingQuery – 发送到数据库的侦测查询,用来检验连接是否处在正常工作秩序中并准备接受请求。默认是“NO PING QUERY SET”,这会导致多数数据库驱动失败时带有一个恰当的错误消息。
6、poolPingEnabled – 是否启用侦测查询。若开启,也必须使用一个可执行的 SQL 语句设置 poolPingQuery 属性(最好是一个非常快的 SQL),默认值:false7、poolPingConnectionsNotUsedFor – 配置 8888、poolPingQuery 的使用频度。这可以被设置成匹配具体的数据库连接超时时间,来避免不必要的侦测,默认值:0(即所有连接每一时刻都被侦测 — 当然仅当 poolPingEnabled 为 true 时适用)。
    还有一种配置JNDI,是通过容器来实现数据源配置额,这里不做介绍,比如使用到proxool或者c3p0时候在介绍。

mappers 标签

    加载实体映射文件的标签,主要形式:
    1、单独加载
    <mappers>
        <mapper url="远程加载"/>
        <mapper resource="本地加载xml"/>
        <mapper class="类加载"/>
    </mappers>
    2、批量加载
    <mappers>
        <mapper name="packge扫描路径"/>
    </mappers>

需要深入的标签,可以了解一下:

typeHandlers 标签

类型处理器,我们从数据源获取数据如何映射到实体类,需要进行转换的,换句话说就是:取数类型如何映射到java类型的处理器。

objectFactory 标签

    mybatis对象的创建使用ObjectFactory,默认实现是DefaultObjectFacotry,如果我们想去改变对象创建时的状态,可以考虑自定义对象工厂。

plugins 标签

有点类似于拦截器,拦截制定的事件和过程,然后增加自己的处理。

上述三个标签,将通过专题形式来展示如何使用已经相关的原理。

项目地址:https://github.com/wzpthq/csdn_mybatis

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值