MyBatis Essentials - core profile (detailed)

  to use MyBatis normally, you first need to configure its core configuration file. The official made it clear that the file should be named mybatis-config.xml
Let's talk about what functions the file has achieved and how to achieve them.
   MyBatis configuration file contains settings and attribute information that will deeply affect MyBatis behavior, and is used by all test classes in this folder. It is recommended to place it in the resources folder during project construction.
   the core configuration file can be found on the MyBatis official website. It will not be repeated, but only the website is attached.
https://mybatis.net.cn/index.html
Get to the point.

The MyBatis configuration file contains settings and attribute information that deeply affect MyBatis behavior.
The top-level structure of the configuration document is as follows:
Next, it will be parsed according to the top-level structure of the configuration file.

configuration

   < configuration > label is the total label containing all labels given in the above figure. All configuration contents shall be included in its label body.

properties

The properties in the < Properties > tab can be configured externally and can be replaced dynamically. These properties can be configured either in a typical Java properties file or in a child element of the < Properties > element.
  take a chestnut: introduce an external configuration file into the core configuration file.

db.properties

driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/mybatis?&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
username = root
password = root

To import the db.properties file into the core configuration file, you can directly import it into the configuration file:

<!--The external configuration file is introduced here. The parameters can be written directly in self closing form without writing-->
<properties resource="db.properties"/>

matters needing attention:
In the configuration file, attributes have their own reading order:
  first, read the attribute specified in the properties element body. Then read the property file under the classpath according to the resource attribute in the properties element, or read the property file according to the path specified by the url attribute, and overwrite the previously read property with the same name.
Finally, read the property passed as a method parameter and overwrite the previously read property with the same name.

When importing an external configuration file, you can also perform some operations on it:

setting

   < setting > tags are very important adjustment settings in MyBatis. They change the runtime behavior of MyBatis. There are detailed records in the official documents and will not be repeated.
Common settings are basically used to increase readability and realize logging function.

typeAliases

  it only sets a short name for Java type, which is only related to XML configuration. Existential meaning is used to reduce the redundancy of class fully qualified names.
There are two ways to alias a single class and specify a package. MyBatis will automatically search for the required Java beans under the package name. By default, all entity classes are named class names (lowercase).

<!--Aliasing a single entity class-->
<typeAliases>
    <typeAlias type="com.wu.pojo.User" alias="User"/>
</typeAliases>

This scheme is recommended when there are few entity classes.

<!--Alias all entity classes under the entire package-->
<typeAliases>
    <typeAlias name="com.wu.pojo"/>
</typeAliases>

This method is recommended when there are many entity classes.
matters needing attention:

  • When aliasing a single entity class, you can customize the alias.
  • If you alias all entity classes under the entire package, you cannot customize the alias.
    (if it must be customized, it can be realized by adding annotations to the required entity classes)
    For example, chestnuts:
import org.apache.ibatis.type.Alias;

//Customize aliases through labels
@Alias("user")
public class User {
	private int id;
	private String name;
	private String password;
}

Other configurations

  • typeHandlers
  • objectFactory (object factory)
  • plugins

There are detailed descriptions in the official documents, which are not the focus of the analysis and are not explained here.

environments

  MyBatis can be configured to adapt to a variety of environments, but each SqlSession instance can only select one environment. Therefore, learn to use and configure multiple sets of operating environments.
The default transaction manager of MyBatis is JDBC, and the type value under the < transactionmanager > tab is "JDBC"
MyBatis connection pool is POOLED, so: < datasource > type = "POOLED"
What is placed in the < property > tab is the specific data connected to the database, which can be changed according to the personal database information.

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

databaseIdProvider

   database vendor ID. MyBatis can execute different statements according to different database vendors. This multi vendor support is based on the databaseId attribute in the mapping statement. MyBatis loads statements with and without the databaseId attribute that match the current database.
  if the same statement with and without databaseId is found at the same time, the latter will be discarded.

  to support the multi vendor feature, simply add < databaseidprovider > to the core configuration file:

<databaseIdProvider type="DB_VENDOR" />

mappers

  now that the behavior of MyBatis has been configured by the above elements, it is time to define the SQL mapping statement. But first, you need to tell MyBatis where to find these statements. Because Java has no effective solution to this problem, we need to manually enter the mapper interface path for binding and registration.
  similarly, it has two ways:
First: register through XML

<!--every last Mapper.xml All need to be in MyBatis Register in core profile-->
<mappers>
    <!--Separation between directories at each level '/' realization-->
    <mapper resource="com/wu/dao/UserMapper.xml"/>
</mappers>

Note that the hierarchical path between resource attributes should be implemented through '/', and the hierarchical format of the configuration file is different from that of ordinary code.

The second is to register through the class file

<mappers>
    <!--Separation between directories at each level '.' realization-->
    <mapper resource="com.wu.dao.UserMapper"/>
</mappers>

matters needing attention:

  • Interface and its Mapper configuration must have the same name
  • The interface and its Mapper configuration file must be in the same package

Write at the end

  finally, attach a complete mybatis-config.xml file containing the header file to realize the standard log factory and open the global cache.
The specific contents will be revised by the watchers themselves. See you next time.

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration Core profile-->
<configuration>
    <!--The external configuration file is introduced here. The parameters can be written directly in self closing form without writing-->
    <properties resource="db.properties"/>

    <settings>
        <!--Standard log factory implementation-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--Explicitly turn on global cache-->
        <setting name="cacheEnabled" value="true"/>
    </settings>

    <!--You can alias an entity class-->
    <typeAliases>
        <typeAlias type="com.wu.pojo.User" alias="User"/>
    </typeAliases>

    <!--Environment configuration-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
            	<!--Value here from db.properties Remove from file-->
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--Binding interface-->
    <mappers>
        <mapper resource="com/wu/dao/UserMapper.xml"/>
    </mappers>
</configuration>

Tags: Java Database Mybatis

Posted on Thu, 07 Oct 2021 03:32:54 -0400 by qing