Mybatis學習筆記(二):Mybatis的配置文件

全局總配置(一份)

想要連接數據庫並對其進行增刪改查,則必須提供一些基本的參數
使用JDBC的方式:
Class.forName(數據庫驅動名稱driverName);
DriverManager.getConnection(url,username,password);
通常我們可以在代碼中直接寫死這些參數,也可以將它們集中的寫在一個properties文件中,通過讀取文件獲取其中配置的參數。

Mybatis本質上是對JDBC的薄封裝,因此它也提供了直接在代碼中寫死和在配置文件中集中配置這些參數的功能,爲了更方便的管理配置信息,Mybatis將配置文件中的所有信息都放在了Configuration對象中。

public class Configuration {

  protected Environment environment;

  protected boolean safeRowBoundsEnabled;
  protected boolean safeResultHandlerEnabled = true;
  protected boolean mapUnderscoreToCamelCase;
  protected boolean aggressiveLazyLoading;
  protected boolean multipleResultSetsEnabled = true;
  protected boolean useGeneratedKeys;
  protected boolean useColumnLabel = true;
  protected boolean cacheEnabled = true;
  protected boolean callSettersOnNulls;
  protected boolean useActualParamName = true;
  protected boolean returnInstanceForEmptyRow;

  protected String logPrefix;
  protected Class <? extends Log> logImpl;
  protected Class <? extends VFS> vfsImpl;
  protected LocalCacheScope localCacheScope = LocalCacheScope.SESSION;
  protected JdbcType jdbcTypeForNull = JdbcType.OTHER;
  protected Set<String> lazyLoadTriggerMethods = new HashSet<>(Arrays.asList("equals", "clone", "hashCode", "toString"));
  protected Integer defaultStatementTimeout;
  protected Integer defaultFetchSize;
  protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
  protected AutoMappingBehavior autoMappingBehavior = AutoMappingBehavior.PARTIAL;
  protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior = AutoMappingUnknownColumnBehavior.NONE;

  protected Properties variables = new Properties();
  protected ReflectorFactory reflectorFactory = new DefaultReflectorFactory();
  protected ObjectFactory objectFactory = new DefaultObjectFactory();
  protected ObjectWrapperFactory objectWrapperFactory = new DefaultObjectWrapperFactory();

  protected boolean lazyLoadingEnabled = false;
  protected ProxyFactory proxyFactory = new JavassistProxyFactory(); // #224 Using internal Javassist instead of OGNL

  protected String databaseId;
  protected Class<?> configurationFactory;

  protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
  protected final InterceptorChain interceptorChain = new InterceptorChain();
  protected final TypeHandlerRegistry typeHandlerRegistry = new TypeHandlerRegistry();
  protected final TypeAliasRegistry typeAliasRegistry = new TypeAliasRegistry();
  protected final LanguageDriverRegistry languageRegistry = new LanguageDriverRegistry();

  protected final Map<String, MappedStatement> mappedStatements = new StrictMap<MappedStatement>("Mapped Statements collection")
      .conflictMessageProducer((savedValue, targetValue) ->
          ". please check " + savedValue.getResource() + " and " + targetValue.getResource());
  protected final Map<String, Cache> caches = new StrictMap<>("Caches collection");
  protected final Map<String, ResultMap> resultMaps = new StrictMap<>("Result Maps collection");
  protected final Map<String, ParameterMap> parameterMaps = new StrictMap<>("Parameter Maps collection");
  protected final Map<String, KeyGenerator> keyGenerators = new StrictMap<>("Key Generators collection");

  protected final Set<String> loadedResources = new HashSet<>();
  protected final Map<String, XNode> sqlFragments = new StrictMap<>("XML fragments parsed from previous mappers");

  protected final Collection<XMLStatementBuilder> incompleteStatements = new LinkedList<>();
  protected final Collection<CacheRefResolver> incompleteCacheRefs = new LinkedList<>();
  protected final Collection<ResultMapResolver> incompleteResultMaps = new LinkedList<>();
  protected final Collection<MethodResolver> incompleteMethods = new LinkedList<>();
  }
  }

在它的構造方法中默認爲我們註冊了以下這些類,當我們需要使用時直接指定別名即可。

public Configuration() {
    typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
    typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);

    typeAliasRegistry.registerAlias("JNDI", JndiDataSourceFactory.class);
    typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class);
    typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class);

    typeAliasRegistry.registerAlias("PERPETUAL", PerpetualCache.class);
    typeAliasRegistry.registerAlias("FIFO", FifoCache.class);
    typeAliasRegistry.registerAlias("LRU", LruCache.class);
    typeAliasRegistry.registerAlias("SOFT", SoftCache.class);
    typeAliasRegistry.registerAlias("WEAK", WeakCache.class);

    typeAliasRegistry.registerAlias("DB_VENDOR", VendorDatabaseIdProvider.class);

    typeAliasRegistry.registerAlias("XML", XMLLanguageDriver.class);
    typeAliasRegistry.registerAlias("RAW", RawLanguageDriver.class);

    typeAliasRegistry.registerAlias("SLF4J", Slf4jImpl.class);
    typeAliasRegistry.registerAlias("COMMONS_LOGGING", JakartaCommonsLoggingImpl.class);
    typeAliasRegistry.registerAlias("LOG4J", Log4jImpl.class);
    typeAliasRegistry.registerAlias("LOG4J2", Log4j2Impl.class);
    typeAliasRegistry.registerAlias("JDK_LOGGING", Jdk14LoggingImpl.class);
    typeAliasRegistry.registerAlias("STDOUT_LOGGING", StdOutImpl.class);
    typeAliasRegistry.registerAlias("NO_LOGGING", NoLoggingImpl.class);

    typeAliasRegistry.registerAlias("CGLIB", CglibProxyFactory.class);
    typeAliasRegistry.registerAlias("JAVASSIST", JavassistProxyFactory.class);

    languageRegistry.setDefaultDriverClass(XMLLanguageDriver.class);
    languageRegistry.register(RawLanguageDriver.class);
  }

比如 transactionManager type="JDBC"和 dataSource type=“POOLED”,這樣寫便代表使用JdbcTransactionFactory.classPooledDataSourceFactory.class作爲它的數據源和事務管理方式

<?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="config.properties"></properties>
    <typeAliases >
        <typeAlias type="com.xxx.pojo.Dept" alias="dept"/>
    </typeAliases>
    <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="com/xxx/mapper/DeptMapper.xml"/>
    </mappers>
</configuration>

配置文件中可以配置的信息

<configuration>
    <properties resource="config.properties"></properties>
    <properties/>
    <settings/>
    <typeAliases/>
    <typeHandlers/>
    <objectFactory/>
    <plugins>
        <plugin interceptor=""></plugin>
    </plugins>
    <environments default="">
        <environment id="">
            <transactionManager type=""></transactionManager>
            <dataSource type=""></dataSource>
        </environment>
    </environments>
    <databaseIdProvider/>
    <mappers/>
</configuration>

以上便是配置文件中可以出現的全部元素了,每個元素出現的順序是固定的,順序不對會報錯

configuration

配置文件根標籤,對應着全局唯一的配置類Configuration,裏面沒有任何屬性可以配置

properties

主要用來讀取配置文件的信息,可以通過url或者resource的方式指定properties文件所在的路徑,它會把配置文件中的信息解析成一個個鍵值對存放在內存中。

settings

可以在這個標籤中配置一些全局的參數,比如是否開啓緩存,是否啓用駝峯命名映射等等。

typeAliases

爲指定的類定義一個別名,在配置文件中使用該類時不需要再寫類的全名,直接使用別名即可,也可以通過指定包的方式爲整個包中的類定義別名,默認爲類名首字母小寫,系統默認定義了一些別名,通過TypeAliasRegistry類可以查看。

typeHandlers

定義類型轉換器,主要作用於映射器工作的時候,即在數據插入時如何將java類型轉換爲jdbc類型,在數據封裝成java對象時如何將jdbc類型轉換爲java類型,系統自定義的類型轉換器在TypeHandlerRegistry類中。

objectFactory

當數據查出來想要封裝到POJO對象中時,objectFactory會創建POJO對象,一般使用其默認提供的便可以實現絕大部分功能了。

plugins

通過插件可以更改sql語句執行的規則。

environments

此標籤底下可以定義多個environment對象,具體使用哪個通過他的default屬性指定,每個enviroment對象對應着一個數據庫連接池配置。

databaseIdProvider

代表了數據庫廠商標識,如果同類型的數據庫,則此標籤沒什麼用。

mappers

指定映射器配置文件所在的路徑,可以單個指定,也可以通過指定包的方式指定。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章