MyBatis2:config.xml file

Source: Internet
Author: User

Objective

The previous article, said MyBatis introduction, talked about the MyBatis has two basic configuration files, one to configure the environment information, one to write SQL statements. The former I named it config.xml,config.xml content is:

 <?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> <typeAliases> <typealias alias= "Student" type= "com.xrq.domain.Student"/> &L t;/typealiases> <environments default= "Development" > <environment id= "Development" > &L T;transactionmanager type= "JDBC"/> <datasource type= "Pooled" > <property name= "Driver                "Value=" Com.mysql.jdbc.Driver "/> <property name=" url "value=" Jdbc:mysql://localhost:3306/test "/> <property name= "username" value= "root"/> <property name= "password" value= "root"/>            ; </dataSource> </environment> </environments> <mappers> <mapper Resource = "Student.xml"/> </mappers></configuration> 

This is the most basic configuration, the general use of MyBatis can be modified on the basis of this configuration file to expand, this article to learn about the CONFIG. s file <configuration></configuration> Some of the content inside.

Typealiases

This tag is not critical, but it is convenient to use MyBatis after the label. Typealiases is a short name for the Java type, which is only related to the XML configuration and is used to reduce the more than part of the class fully qualified name, for example:

<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>

With this configuration, "Blog" can be used in place of "Domain.blog.Blog".

Environments

MyBatis can configure multiple environments, which will help you apply SQL maps to multiple databases. For example, you might want to set up a different configuration, test, and production environment for development. Or you might have multiple production-level databases that share the same pattern, so you'll think of using the same SQL mappings for different databases. This usage is the most.

One important issue is that you can configure multiple environments, but you only have to select one for each sqlsessionfactory instance .

So, if you want to connect two databases, you need to create two sqlsessionfactory instances , one for each database. In the case of three databases, you need three instances, and so on. Let's take a look at the front environments:

<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/test "/>            <property name=" username " value= "root"/>            <property name= "password" value= "root"/>        </dataSource>    </ Environment></environments>

and the corresponding Java code is:

Reader = Resources.getresourceasreader ("config + +"); SSF = new Sqlsessionfactorybuilder (). build (reader);

The Sqlsessionfactorybuilder build method actually has several other overloaded methods, one of which is important:

Public sqlsessionfactory build (reader Reader, String environment) {    return build (reader, environment, NULL);}

The principle is that if you pass in environment, the specified envrionment is bound to sqlsessionfactory, and if you do not pass in environment, The environment specified by default is bound to Sqlsessionfactory.

Then look at the environment elements:

1, TransactionManager

There are two types of things manager in MyBatis, one is JDBC and the other is managed.

    • JDBC----This configuration simply uses the JDBC commit and rollback settings, which depend on the connection the data source gets to manage the scope of things
    • MANAGED----This configuration almost does nothing. It never commits or rolls back a connection, and it allows the container to manage the entire life cycle of the thing (such as the context of the spring or Java EE Application Server), and by default it closes the connection, but some containers do not want it, so if you need to stop it from the connection, Set the CloseConnection property to False, for example:
      <transactionmanager type= "MANAGED" >    <property name= "CloseConnection" value= "false"/></ Transactionmanager><transactionmanager type= "MANAGED" >

2, DataSource

The datasource element uses the basic JDBC data source interface to configure the resources of the JDBC Connection object. Many MyBatis applications will configure the data source according to the example above, but it is not necessary to know that the data source is necessary for the convenience of using lazy loading. There are three types of built-in data sources (i.e. type= "XXX"):

(1) unpooled

The implementation of this data source is to open and close the connection each time it is requested. It is a bit slow, this is a good choice for simple applications, because it does not require a timely connection, different databases on this performance is not the same, so for some database configuration data source is not important, this configuration is idle. The unpooled type of data source is used only to configure the following six properties:

    • Driver----This is the fully qualified name of the JDBC-driven Java class
    • URL----This is the JDBC URL address of the database
    • Username----User name of the login database
    • Password----The password for the login database
    • Defaulttransactionisolationlevel----The default connection thing isolation level
    • driver.encoding----Pass database-driven properties prefixed with "driver." At the beginning, "driver.encoding" means passing the encoding property.

(2) Pooled

This is the implementation of the data source connection pool for the JDBC Connection object to avoid the necessary connection and authentication time when creating a new connection instance. This is a popular way for the current Web application to respond quickly to requests. In addition to the above (unpooled) properties, there are other properties that you can use to configure the pooled data source:

    • Poolmaximumactiveconnections----The number of active (i.e. in use) connections that exist at any time, with a default value of 10
    • Poolmaximumidleconnections number of idle connections that exist at any time----
    • Poolmaximumcheckouttime----The time the connection is checked in the pool before it is forced to return, the default value is 2000 milliseconds or 20 seconds
    • Pooltimetowait, Poolpingquery, poolpingenabled, poolpingconnectionsnotusedfor----These are some of the properties that detect database connections

(3) JNDI

This data source is implemented to use containers such as spring or application server, where the container can either centralize or externally configure the data source and then place a reference to the JNDI context. This data source requires only two properties:

    • Initial_context----This property is used to look for the environment from the initial context, this is an optional attribute, and if omitted, then the data_source property will be searched directly for the background InitialContext
    • Data_source----This is the context path referencing the location of the data source instance, which is looked up in the context of the environment returned by the Initial_context query, and if Initial_context does not return a result, it directly looks for the environment as the initial context

Similar to other data source configurations, it can also be done by using the name "env." The prefix sends properties directly to the initial context.

Mappers

Since MyBatis's behavior has been configured by the above elements, the following defines the SQL mapping statement, but first we need to tell MyBatis where to look for these statements. Java does not provide a good way to do this, so the best way is to tell MyBatis where to look for the mapping file, either by using a resource reference relative to the path, or by a character representation, or by the fully qualified name of the URL reference, for example:

Use resources relative to Classpath <mappers>    <mapper resource= "Org/mybatis/builder/authormapper.xml"/>    <mapper Resource= "Org/mybatis/builder/blogmapper.xml"/>    <mapper resource= "Org/mybatis/builder/postmapper.xml" /></mappers>//using fully qualified paths <mappers>    <mapper url= "File:///var/sqlmaps/AuthorMapper.xml"/>    <mapper url= "File:///var/sqlmaps/BlogMapper.xml"/>    <mapper url= "file:///var/sqlmaps/ Postmapper.xml "/></mappers>

These statements simply tell MyBatis where to find the mapping file, and the rest of the details are in each SQL mapping file, which is discussed in the following article.

Settings

The first few are in config. s, the following is a property, this attribute can not appear in the config, but more important, written here in order to see later.

This property is settings and is a very important adjustment, and they will change the way MyBatis behaves at runtime. This table describes the settings information, their meanings, and the default values:

Parameter settings Describe Valid values Default value
Cachedenabled Used to configure the global mapper to enable or disallow caching True|false

True

Lazyloadingenabled Enables or disables lazy loading globally. When disabled, all associated objects are loaded instantly True|false True
Aggressivelazyloading When enabled, objects with lazy load properties will fully load any property when called, otherwise each property will be loaded as needed True|false True
Multipleresultsetsenabled Allow or disallow multiple result sets to be returned from a single statement (requires an appropriate driver) True|false True
Usecolumnlabel Use column labels instead of column names. Different drivers behave differently in this regard, refer to drive documentation or fully test two methods to determine which driver is used True|false True
Usegeneratedkeys Allows JDBC to support the generated keys and requires a suitable driver. If set to true then this driver forces the generated key to be used, although some drivers are rejected for compatibility but still valid. True|false True
Automappingbehavior Specifies how MyBatis automatically maps columns to fields/properties partial only automatically maps simple, non-nested results. Full will automatically map arbitrarily complex results. none| partial| Full PARTIAL
Defaultexecutortype Configures the default executor. The simple actuator is nothing special, and the reuse executor uses preprocessing statements, batch Executor-statements, and batch updates. simple| reuse| BATCH Simple
Defaultstatementtimeout Sets the time-out period, which determines when the driver waits for a database response. Any positive integer Not Set (NULL)

An example configuration for a complete set of information elements is as follows:

<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= "Enhancementenabled" value= "false"/>    <setting name= "Defaultexecutortype" value= "simple"/>    < Setting name= "Defaultstatementtimeout" value= "25000"/></settings>

The main configuration information in config. Settings is almost the above, the first three are more important, the high-level settings, the need for more experienced development to adjust according to the project situation.

A later article will explore the mapping of SQL statements, which is also the core of MyBatis.

MyBatis2:config.xml file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.