Mybatis learning - configuration analysis

Keywords: Java Database Back-end SSM

front word : \textcolor{green} {Preface:} preface:
💞 In the previous article, we learned what Mybatis is and also wrote our first Mybatis program. Next, let's take a look at the important configuration analysis 💞

💝 The code involved in the following article can be found on my gitee 💥 Learn MyBatis source code💥
📞 I don't know how to download it. You can read this article and learn this skill. It's very nice 🌏 How to use Git🌏

Official configuration resolution website

1. Core profile

  • mybatis-config.xml

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

    properties(Properties)
    settings(Settings)
    typeAliases(Type alias)
    typeHandlers(Type (processor)
    objectFactory(Object factory)
    plugins(Plug in)
    environments(Environment configuration)
    environment(Environment variables)
    transactionManager(Transaction manager)
    dataSource((data source)
    databaseIdProvider(Database (vendor ID)
    mappers(Mapper)
    

2. Environment configuration

  • MyBatis can be configured to adapt to a variety of environments
  • The default transaction manager of Mybatis is JDBC and the connection pool is POOLED
  • Although multiple environments can be configured, only one environment can be selected for each SqlSessionFactory instance.
<environments default="development">
  <environment id="development">
    <transactionManager type="JDBC">
      <property name="..." value="..."/>
    </transactionManager>
    <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>

Note some key points:

  • The default environment ID (for example, default = "development").
  • The environment ID defined by each environment element (for example: id = "development").
  • Configuration of the transaction manager (for example: type = "JDBC").
  • Configuration of data source (for example, type = "POOLED").

The default environment and environment ID are as the name suggests. The environment can be named at will, but make sure that the default environment ID matches one of the environment IDs.

If the environment needs to be switched, we need to add an environment, then modify the id to be unique, and finally modify the default to the required environment

Transaction manager and data source:

  • Transaction manager: there are two types of transaction managers in MyBatis (that is, type="[JDBC|MANAGED]"

  • data source

POOLED – the implementation of this data source uses the concept of "pool" to organize JDBC connection objects, avoiding the initialization and authentication time necessary to create new connection instances. This processing method is very popular and can enable concurrent Web applications to respond to requests quickly.

In addition to the above mentioned attributes under UNPOOLED, there are more attributes to configure the data source of POOLED:

  • poolMaximumActiveConnections – the number of active (in use) connections that can exist at any time. Default: 10
  • poolMaximumIdleConnections – the number of idle connections that may exist at any time.
  • poolMaximumCheckoutTime – the time that connections in the pool are checked out before being forcibly returned. The default value is 20000 milliseconds (i.e. 20 seconds)
  • poolTimeToWait – this is an underlying setting. If it takes a long time to obtain a connection, the connection pool will print the status log and try to obtain a connection again (to avoid continuous failure in case of misconfiguration and no log printing). The default value is 20000 milliseconds (i.e. 20 seconds).
  • poolMaximumLocalBadConnectionTolerance – this is a low-level setting on bad connection tolerance. It applies to every thread trying to get a connection from the cache pool. If the thread gets a bad connection, the data source allows the thread to try to get a new connection again, but the number of retries should not exceed poolmaximum Sum of umidleconnections and poolMaximumLocalBadConnectionTolerance. Default: 3 (added to 3.4.5)
  • poolPingQuery – a probe query sent to the database to verify that the connection is working properly and ready to accept the request. The default is "NO PING QUERY SET", which will cause most database drivers to return appropriate error messages when errors occur.
  • poolPingEnabled - whether to enable detection query. If enabled, you need to set the poolPingQuery property to an executable SQL statement (preferably a very fast SQL statement). The default value is false.
  • poolPingConnectionsNotUsedFor – configure the frequency of poolPingQuery. It can be set to the same as the database connection timeout to avoid unnecessary detection. The default value is 0 (that is, all connections are detected at every moment - of course, it only applies when poolPingEnabled is true).

3. properties

We can reference the configuration file through the properties property

These properties can be configured externally and can be replaced dynamically. You can configure these properties either in a typical Java properties file or in a child element of the properties element

3.1 write a configuration file

Add db.properties under resources

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
  • Introduced in the core configuration file.

Note that the order problem properties must be at the top, otherwise an error will be reported.

<!--Import external profile-->
<properties resource="db.properties"/>

mybatis-config.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">
<!--Core profile-->
<configuration>
    <!--Import external profile-->
    <properties resource="db.properties"/>


    <environments default="development">
        <environment id="development">
            <!--transaction management-->
            <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>
    <!--every last Mapper.xml All need to be in Mybatis Register in core profile-->
    <mappers>
        <mapper resource="com/hxl/dao/UserMapper.xml"/>
    </mappers>

</configuration>
  • You can also add some attribute configurations, that is, do not write the account password in db.properties. Write it under xml
<!--Import external profile-->
<properties resource="db.properties">
    <property name="username" value="root"/>
    <property name="password" value="123456"/>
</properties>
  • If the two files have the same field, the external configuration file under db.properties is preferred.

3.2 test:

This problem occurred while running:

terms of settlement:

<resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
</resource>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <configuration>
            <encoding>UTF-8</encoding>
        </configuration>
    </plugin>
</plugins>

4. Type aliases

  • A type alias can set an abbreviated name for a Java type. It is only used for XML configuration and is intended to reduce redundant writing of fully qualified class names. For example:
<typeAliases>
  <typeAlias alias="Author" type="domain.blog.Author"/>
  <typeAlias alias="Blog" type="domain.blog.Blog"/>
</typeAliases>

Example: pay attention to the sequence position

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

After writing, you can use the fully qualified class name to reduce redundancy. The following is an example

When configured in this way, Blog can be used anywhere domain.blog.Blog is used.

  • You can also specify a package name. MyBatis will search for the required Java beans under the package name, such as:

    Scan the package of an entity class, and its default alias is the class name of the class, with the first letter in lowercase

<!--You can alias an entity class-->
<typeAliases>
    <package name="com.hxl.pojo"/>
</typeAliases>

  • How to use it

    The first method is used when there are few entity classes

    If there are many entity classes, the second one is recommended

    The difference between the two: the first can be diy, that is, a user-defined alias, and the second can't

    But the second can specify aliases through annotations

    import org.apache.ibatis.type.Alias;
    @Alias("hhh")
    public class User
    

    In this way, hhh can be used instead of user

5. Setting

This is a very important adjustment setting in MyBatis, which will change the runtime behavior of MyBatis. The following table describes the meaning, default values, etc. of each setting in the setting.

https://mybatis.org/mybatis-3/zh/configuration.html#settings

Set namedescribeEffective valueDefault value
cacheEnabledGlobally turn on or off any cache configured in all mapper profiles.true | falsetrue
lazyLoadingEnabledGlobal switch for delayed loading. When on, all associated objects are loaded late. In a specific association, the switch state of the item can be overridden by setting the fetchType property.true | falsefalse
useGeneratedKeysJDBC is allowed to support automatic generation of primary keys, which requires database driver support. If set to true, the auto generated primary key is enforced. Although some database drivers do not support this feature, they still work (such as Derby).true | falseFalse
mapUnderscoreToCamelCaseWhether to enable automatic hump naming mapping, that is, from the classic database column name A_COLUMN maps to the classic Java property name aColumn.true | falseFalse
logImplSpecify the specific implementation of the log used by MyBatis. If it is not specified, it will be found automatically.SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGINGNot set

6. Other configurations

  • typeHandlers
  • objectFactory (object factory)
  • plugins
    • mybatis-generator-core
    • mybatis-plus
    • General mapper

7. mappers

MapperRegistry: register and bind our Mapper file

<!-- Use resource references relative to Classpaths -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
<!-- Use the mapper interface to implement the fully qualified class name of the class -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
<!-- Register all the mapper interface implementations in the package as mappers -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

Method 1: [recommended]

<!--every last Mapper.xml All need to be in Mybatis Register in core profile-->
<mappers>
    <mapper resource="com/hxl/dao/UserMapper.xml"/>
</mappers>

Method 2: register with class file binding

<!--every last Mapper.xml All need to be in Mybatis Register in core profile-->
<mappers>
    <!--<mapper resource="com/hxl/dao/UserMapper.xml"/>-->
    <!--If UserMapper and UserMapper.xml If it is not under one package, an error will be reported-->
    <mapper class="com.hxl.dao.UserMapper"></mapper>
</mappers>

Note:

  • Interface and its Mapper configuration file must have the same name
  • Interface and its Mapper configuration file must be under the same package

Method 3: use scan package for injection binding

<!--every last Mapper.xml All need to be in Mybatis Register in core profile-->
<mappers>
    <!--<mapper resource="com/hxl/dao/UserMapper.xml"/>-->
    <!--<mapper class="com.hxl.dao.UserMapper"></mapper>-->
    <package name="com.hxl.dao"/>
</mappers>

Note:

  • Interface and its Mapper configuration file must have the same name
  • Interface and its Mapper configuration file must be under the same package

8. Life cycle

Lifecycle and scope are critical, because incorrect use can lead to very serious concurrency problems.

SqlSessionFactoryBuilder

  • Once SqlSessionFactory is created, it is no longer needed
  • local variable

SqlSessionFactory:

  • It can be imagined as: database connection pool

  • Once SqlSessionFactory is created, it should always exist during the operation of the application. There is no reason to discard it or recreate another instance.

  • The best scope of SqlSessionFactory is the application scope

  • The simplest is to use singleton mode or static singleton mode

SqlSession

  • A request to connect to the connection pool
  • The instance of SqlSession is not thread safe, so it cannot be shared, so its best scope is the request or method scope
  • The request needs to be closed after it is used up, otherwise the resources will be occupied

  • Each Mapper here represents a business

Posted by Patioman on Sat, 06 Nov 2021 16:41:08 -0700