Mybatis learning notes: mybatis configuration analysis

1, Mybatis core profile

Core configuration file: 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:

configuration(Configuration)
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 configurations

mybatis can configure multiple environments to map SQL to different databases. For example, the databases of development, test and production environments are different and need different configurations. However, although multiple environments can be configured, only one environment can be selected for each SqlSessionFactory instance. You need as many SqlSessionFactory instances as there are environments.

SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, environment);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader, environment, properties);

Pass environment as a parameter to instantiate different factories. If the environment parameter is ignored, the default environment is loaded.

<!--    default Is the default environment-->
    <environments default="development">
<!--        id by development Environment-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="org.postgresql.Driver"/>
                <property name="url" value="jdbc:postgresql://127.0.0.1:5432/postgres?useSSL=false"/>
                <property name="username" value="postgres"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
<!--        id by test Environment-->
        <environment id="test">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED"></dataSource>
            ...
        </environment>
    </environments>

**Transaction manager) * * has two configurations: type = "[JDBC managed]"

  • JDBC: uses JDBC's commit and rollback facilities.
  • MANAGED: this configuration does little. It never commits or rolls back a connection, but lets the container manage the entire life cycle of the transaction.

**There are three types of dataSource) * * type="[UNPOOLED|POOLED|JNDI]"

  • UNPOOLED – the implementation of this data source opens and closes the connection each time it is requested.
  • 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. The default is this.
  • JNDI – this data source implementation is intended to be used in containers such as EJB s or application servers.

3, properties

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.

<dataSource type="POOLED">
  <property name="driver" value="${driver}"/>
  <property name="url" value="${url}"/>
  <property name="username" value="${username}"/>
  <property name="password" value="${password}"/>
</dataSource>

That is, the value of the property tag can be dynamically changed through external configuration.

Write a db.properties

driver=org.postgresql.Driver
url=jdbc:postgresql://127.0.0.1:5432/postgres?useSSL=false
username=postgres
password=123456

Add the < Properties > tag in the core configuration file, but there is a problem here. The tags in xml are not added casually, and there must be a sequence, because they are loaded from the beginning.

Introduce db.properties into the core configuration of mybatis and modify the < property > tag in the environment configuration as follows:

<configuration>
    <properties resource="db.properties">
<!--        <property name="username" value="dev_user"/>-->
<!--        <property name="password" value="F2Fa3!33TYyg"/>-->
    </properties>
    <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/hjxlog/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

At this time, ${driver},${url} equivalent will be read from the db.properties file.

At the same time, you can also pass in the attribute value in the SqlSessionFactoryBuilder.build() method.

If there are configuration attribute values in these three places, the reading order of mybatis is:

  1. First read the < property > attribute value in the < Properties > tag;

  2. Read the attribute value of db.properties introduced by < properties resource = "dB. Properties" > again. If there are the same, the value of < property > will be overwritten with the value of db.properties;

  3. Finally, read the property passed as a method parameter and overwrite the previously read property with the same name.

In addition, you can also use the default value, that is, if the attribute to be read is not read, the default value can be used:

<dataSource type="POOLED">
  <!-- ... -->
  <property name="username" value="${username:ut_user}"/> <!-- If attribute 'username' Not configured,'username' The value of the property will be 'ut_user' -->
</dataSource>

However, the premise of using the default value is to turn on the default value property, that is:

    <properties resource="db.properties">
<!--        <property name="username" value="dev_user"/>-->
<!--        <property name="password" value="F2Fa3!33TYyg"/>-->
        <property name="org.apache.ibatis.parsing.PropertyParser.enable-default-value" value="true"/> <!-- Enable default value property -->
    </properties>

4, Type aliases

Type alias sets an abbreviated name for a Java type. It is only used for XML configuration and is intended to reduce redundant fully qualified class name writing.

4.1 configure in Mybatis core configuration file

The configuration here is configured in the core configuration file of Mybatis.

    <typeAliases>
        <typeAlias alias="User" type="com.hjxlog.domain.User"/>
    </typeAliases>

Replace the full path of the Java class with an alias, which is used in xml.

4.2 scanning package

You can also specify a package name. MyBatis will search for the required Java Bean under the package name and use the initial lowercase unqualified class name of the bean as its alias.

    <typeAliases>
        <package name="com.hjxlog.domain"/>
    </typeAliases>

4.3 notes

Alias with annotations:

@Alias("theUser")
public class User {
}
    <select id="selectUserList" resultType="theUser">
        select * from public.user
    </select>

Among them, the configuration priority in the mybatis core configuration file is the highest. If there are other configuration comments after package scanning, the comments shall prevail.

Alias of Java type, if underlined, The mapping is the basic type. If it is not underlined, the mapping is the wrapper type.

5, settings

These are extremely important tuning settings in MyBatis, which change the runtime behavior of MyBatis.

Learn about several common:

  • cacheEnabled: globally turns on or off any cache configured in all mapper configuration files.
  • Lazy loading enabled: global switch for lazy 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.
  • Usegenerated keys: allows JDBC to support automatic generation of primary keys, which requires database driver support.
  • mapUnderscoreToCamelCase: whether to enable automatic hump naming mapping, that is, from the classic database column name A_COLUMN maps to the classic Java property name aColumn.
  • logImpl: Specifies the specific implementation of the log used by MyBatis. If it is not specified, it will be found automatically.

6, mappers

The mapper tells MyBatis where to find these statements.

Mode 1:

<!-- Use resource references relative to Classpaths -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
</mappers>

Mode 2:

<!-- Use fully qualified resource locators( URL) -->
<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
  <mapper url="file:///var/mappers/BlogMapper.xml"/>
</mappers>

Mode 3:

<!-- 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"/>
</mappers>

be careful:

  • Interface and mapper files must have the same name
  • The interface and mapper files are in the same package

Mode 4:

<!-- Register all the mapper interface implementations in the package as mappers -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

Tags: Back-end

Posted on Mon, 29 Nov 2021 12:16:09 -0500 by Nickosssss