MyBatis configuration file Detailed

Source: Internet
Author: User

The MyBatis environment built with MAVEN, the directory structure is as follows

  

Configuration file in Src/main/resources directory, is Configuration.xml

1: First look at the simple configuration:

  

<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE Configuration Public "-//mybatis.org//dtd Config 3.0//en" "Mybatis-3-config.dtd"><Configuration>    <!--You can configure multiple run environments, but each sqlsessionfactory instance can only select one running environment -    <Environmentsdefault= "Work">        <EnvironmentID= "Work">            <TransactionManagertype= "JDBC"></TransactionManager>            <!--unpooled Pooled JNDI -            <DataSourcetype= "unpooled">                < Propertyname= "Driver"value= "Com.mysql.jdbc.Driver" />                < Propertyname= "url"value= "Jdbc:mysql://localhost:3306/mybatis" />                < Propertyname= "username"value= "root" />                < Propertyname= "Password"value= "Password" />            </DataSource>        </Environment>    </Environments>    <mappers>        <MapperResource= "Com/zhao/mapper/studentmapper.xml"/>    </mappers></Configuration>

Congfiguration: root element

<configuraion>

Environments: Configure the MyBatis environment, you can configure a running environment, but sqlsessionfactory can only select one running environment

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

TransactionManager: Transaction manager

TYPE=JDBC or Managed

JDBC: Using the JDBC Commit and rollback settings;

MANAGED: Let the container manage the entire life cycle of the transaction

<transactionmanager type= "JDBC" ></transactionManager>
DataSource: Data source

The DataSource element uses the standard JDBC data source interface to configure the JDBC Connection object source.

There are three types of data sources built into the MyBatis:

unpooled – The implementation of this data source is to simply open and close the connection each time it is requested. It's a little bit slow, which is a good choice for simple applications because it doesn't need to be available in a timely connection. Different databases for 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 5 properties:

        • Driver – This is the fully qualified name of the JDBC-driven Java class (If your driver contains it, it is not a data source class).
        • URL – This is the JDBC URL address for the database.
        • Username – The user name of the login database.
        • Password – The password for the login database.
        • defaulttransactionisolationlevel – The default connection transaction isolation level.

As an option, you can pass database-driven properties. To do this, the property is prefixed with "driver." The beginning, for example:

        • Driver.encoding=utf8

This will pass the property "encoding" with the value "UTF8", which is passed to the database driver through the Drivermanager.getconnection (url,driverproperties) method.

Pooled – This is the implementation of the data source connection pool for the JDBC connection object to avoid the necessary initial 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 many properties that you can use to configure the pooled data source:

            poolmaximumactiveconnections – The number of active (that is, in use) connections that exist at any time. Default value: 10

            poolmaximumidleconnections – The number of idle connections that exist at any time.

        • Poolmaximumcheckouttime – The time that the connection in the pool was checked before it was forced to return. Default value: 20000 milliseconds (i.e. 20 seconds)
        • pooltimetowait – This is a low-level setting that gives the connection Pool A print log status opportunity, and a retry to get the connection, which often takes a long time to avoid a silent failure when the connection pool is not configured. Default value: 20000 milliseconds (i.e. 20 seconds)
        • Poolpingquery – A reconnaissance query sent to the data to verify that the connection is working properly and is ready to accept the request. The default is "NO PING QUERY SET", which causes many database-driven connections to fail with an error message.
        • poolpingenabled – This is to turn reconnaissance queries on or off. If you turn it on, you must set the Poolpingquery property with a valid SQL statement (preferably very fast). Default value: False.
        • Poolpingconnectionsnotusedfor – This is used to configure poolpingquery multiple times to be used once. This can be set to match the standard database connection timeout time to avoid unnecessary detection. Default value: 0 (that is, all connections are detected at every moment-but only when poolpingenabled is true).

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 configuration requires only two properties:

        • Initial_context – This property is used to look for the environment from the initial context (that is, Initialcontext.lookup (Initial--context). This is an optional attribute, and if omitted, the Data_source property will be looked up directly in InitialContext as the background.
        • Data_source – This is the path to the context that references the location of the data source instance. It is located in the context of the environment returned by the Initial_context query, and if Initial_context does not return a result, it is located directly in the context for the environment.

Similar to other data source configurations, it can also send properties directly to the initial context through a prefix called "env." Like what:

      • Env.encoding=utf8

After initialization, this will pass the property named "Encoding" to the constructor of the initial context with the value "UTF8".


<datasource type= "unpooled" >
<property name= "Driver" value= "Com.mysql.jdbc.Driver"/>
</dataSource>
</environment>
</environments>

Mapper: Specifying a mapping file or a mapping class

<mappers>

<mapper resource= "Com/zhao/mapper/studentmapper.xml"/>
</mappers>

</configuration>:

2:studentmapper.xml

<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Mybatis-3-mapper.dtd "><Mappernamespace= "Com.zhao.mapper.StudentMapper">    <InsertID= "Savestudent"ParameterType= "Com.zhao.entity.Student">INSERT into student values (Default,#{name},#{password})</Insert></Mapper>

This is a simple insert process, our parametertype is a full path com.zhao.entity.Student, if each is written so full words will be very troublesome, so we can configure its alias, of course, Aliases to be configured in Configuration.xml

    < typealiases >        <  type= "Com.zhao.entity.Student"  alias= "Student"/>    </typealiases>

Later studentmapper.xml in the direct write student just good, so see more convenient.

With so much to do at the moment, Configuration.xml said it first.

Let's talk about Studentmapper.xml, which defines some of our operations in this file, such as insert delete Select, and we all have tags. There are two main things to remember in this configuration file, one is

The namespace property of the <mapper> tag, which we use to navigate to this configuration file. There is another one is <resultmap>, this is the most interesting.

 Packagecom.zhao.entity; Public classStudent {Private intID; PrivateString name; PrivateString password;  PublicStudent () {} PublicStudent (string name, string password) { This. Name =name;  This. Password =password; }     Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; } @Override PublicString toString () {return"Student [id=" + ID + ", name=" + name + ", password=" + password + "]"; }}

You can see that the columns of our data table and the properties of the entity classes are not the same, so we need to do a simple configuration. What we do with insertions may not be as obvious if we're doing a query operation

    <id= "Selectstudentbyid"  parametertype= "int"   Resulttype= "Student">        select * from Student where stu_id=#{id}     </ Select >

Before we have set the alias, Resulttype can be written directly student, do not write com.zhao.entity.Student. The next Test

    @Test    publicvoidthrows  ioexception {        reader reader= Resources.getresourceasreader ("Configuration.xml");        Sqlsessionfactory Factory=new  Sqlsessionfactorybuilder (). build (reader);        sqlsession session=factory.opensession ();                Student Student=session.selectone ("Com.zhao.mapper.StudentMapper.selectStudentById", 1);        SYSTEM.OUT.PRINTLN (student);        Session.commit ();        Session.close ();    }

The return value is null, and obviously the content we've looked up from the database is stu_id stu_name Stu_password, but our return value type is student and there's no way to complete the encapsulation, so we need resultmap

    <Resultmaptype= "Student"ID= "Result">        <IDcolumn= "stu_id" Property= "id"/>        <resultcolumn= "Stu_name" Property= "Name"/>        <resultcolumn= "Stu_password" Property= "Password"/>    </Resultmap>

Here the student is still our alias, and then complete the one by one correspondence through the content below. And in Select, you need to write resultmap= "result".

Next Test

This is the right result.

MyBatis configuration file Detailed

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.