(4) Mybatis from entry to soil-aliases, configuration files and the introduction of mapper

This is the fourth in the mybatis series. If you haven’t read the previous suggestions, first go to the [Java Tsuka Fox] public account to view the previous articles, which is convenient for understanding and grasping.

Alias

Why do you need to use aliases?

There are many places in the xml file that require the complete class name of the class, which is very verbose. In order to reduce our workload and complexity, mybatis supports us to give an alias to a certain class, and then we can access the specified type through the alias.

Usage of alias

Before using an alias, you need to register an alias in mybatis, and there are three ways to register an alias.

Way 1

Use the typeAlias ​​element to register

as follows:

<typeAliases>
    <typeAlias type="完整的类型名称" alias="别名" />
</typeAliases>

The typeAliases element can contain multiple typeAlias ​​sub-elements. Each typeAlias ​​can register an alias for a type. There are two attributes that need to be specified:

  • type: full type name
  • alias: alias

Way 2

Batch registration via packege element

Above we can register an alias through the typeAlias ​​element. If we have many classes to register, we need to write a lot of typeAlias ​​configuration.

Mybatis provides us with a way to register aliases in batches, through the package element, as follows:

<typeAliases>
    <package name="需要扫描的包"/>
</typeAliases>

This is also under the typeAliases element, but this time the package element is used. The package has a name attribute, which can specify a package name. Mybatis will load this package and all types in subpackages, and register aliases and alias names for these types. By default, the class name will be lowercased, for example , the alias of UserModel is usermodel

Way 3

Package combined with @Alias ​​to register in batches and assign aliases

In method 2, aliases can be registered in batches through packages, but multiple classes with the same class name are prone to appear.

So when registering aliases in batches in package mode, we can add an @Alias ​​annotation to the class to assign aliases to this class:

@Alias("user")
public class UserModel {
}

When mybatis scans the class, it finds that there is an Alias ​​annotation on the class, and will take the value of this annotation as the alias. If there is no such annotation, the lowercase of the class name will be used as the alias, as in method 2.

Aliases are not case sensitive

Mybatis provides aliases for many types by default

The principle of alias

Mybatis allows us to register an alias for a certain type. A mapping relationship will be established between the alias and the type. This mapping relationship is stored in a map object. The key is the name of the alias and the value is the specific type. When we access a certain type by a name In the case of a type, mybatis first searches the map of the alias and type mapping according to the key according to the name of the type. If it finds the corresponding type, it will directly return the corresponding type. If it is not found, it will use this name as the complete class name to resolve it. For the Class object, if this type is not recognized in these two steps of analysis, an error will be reported.

Suggestions for using aliases

The way of aliasing can simplify the writing of types. Originally a long list of UserModel objects, now you only need to write a user, which is very convenient and concise to use. But in terms of maintenance, it is not very convenient.

Therefore, it is recommended that custom classes do not use aliases as much as possible, and we need to know some of the built-in aliases in mybatis.

Detailed attribute configuration file

The configuration of connecting to the database is written directly in the mybatis global configuration file, but after going online, some changes may be required to switch the database, which is not very optimized, so we usually add some configuration information that needs operation and maintenance (such as: db Configuration, mail configuration, redis configuration, etc.) are placed in a properties configuration file, and then when it goes online, only operation and maintenance are required to modify this configuration file, and they do not need to modify the code-related files at all.

Mybatis also supports us to configure some property information through external properties files.

There are 3 ways to configure attribute information in mybatis.

Method 1: Define properties in the property element

Attribute definition

The property information is defined by the properties element in the mybatis global configuration file, as follows:

<configuration>
    <properties>
        <property name="属性名称" value="属性对应的值"/>
    </properties>
</configuration>

The property information is configured through the property element above:

  • name: the name of the attribute
  • value: The value of the attribute.

Such as:

<property name="jdbc.driver" value="com.mysql.jdbc.Driver"/>
Use ${property name} to refer to the value of the property

The attribute has been defined, we can refer to the value of the defined attribute through ${attribute name}, such as:

<property name="driver" value="${jdbc.driver}"/>

Method 2: Resource import configuration file

In method 1, our configuration file is still written in the global configuration file. Mybatis supports importing the configuration file from the outside, and the configuration file can be written in other external files and then imported.

Import the configuration file in the classes path
<configuration>
    <properties resource="配置文件路径"/>
</configuration>

The properties element has a resource attribute, which is the path of the configuration file relative to the classes. The configuration file is usually placed in the src/main/resource directory. The files in this directory will be placed in the classes path after compilation.

Method 3: Import remote configuration files by url

Mybatis also provides a way to import remote configuration files, as follows:

<properties url="远程配置文件的路径" />

This time the properties element is still used, but the url attribute is used, such as:

<properties url="http://itsoku.com/properties/config.properties" />

Recommendations for using property configuration files

We talked about 3 methods above. The second method is a more common method. It is recommended that you can use the second method to introduce external resource configuration files.

If we have written all three ways, how will mybatis go?

  • When both mode 1 and mode 2 exist, the configuration of mode 2 will overwrite the configuration of mode 1.
  • If both method 2 and method 3 exist, method 3 will be invalid

Mybatis will first read the configuration of mode 1, and then read the configuration of mode 2 or mode 3, and will overwrite the same configuration in 1.

3 ways to introduce mapper in mybatis

The mapper xml file is very important. The sql we write is basically in it. When using mybatis to develop a project, most of the code related to mybatis is to write sql, basically dealing with mapper xml.

The prepared mapper xml needs to be known to mybatis, how do we let mybatis know?

It can be imported through the mybatis global configuration file, there are three main ways.

Method 1: Use the mapper resouce attribute to register the mapper xml file

At present, the various examples we are involved in are adopted in this way, using the following methods to introduce:

<mappers>
    <mapper resource="Mapper xml的路径(相对于classes的路径)"/>
</mappers>

Precautions

  • Under normal circumstances, we will create a Mapper interface with the same name as the namespace in the Mapper xml, and the Mapper interface will be bound to the Mapper xml file
  • When mybatis loads the mapper xml, it will find the Mapper interface corresponding to the namespace, and then register, we can access the specific operations in the Mapper xml through the Mapper interface
  • The cooperation of Mapper xml and Mapper interface is a relatively common practice, and it is strongly recommended for everyone to use it.

Method 2: Use the mapper class attribute to register the Mapper interface

Introduce the Mapper interface

The mapper interface is introduced in the mybatis global configuration file as follows:

<mappers>
        <mapper class="接口的完整类名" />
</mappers>

In this case, mybais will load the interface corresponding to the class, and then load the xml file with the same name in the same directory as this interface.

Such as:

<mappers>
        <mapper class="zhonghu.chat01.demo1.UserMapper" />
</mappers>

With the above wording, mybatis will automatically register the UserMapper interface, and will also look for the following files:

zhonghu.chat01.demo1.UserMapper.xml

It is estimated that you will see this way of writing when you develop projects in the future. The Mapper interface and the Mapper xml file are placed in the same package.

Method 3: Use the package element to register Mapper interfaces in batches

Batch register Mapper interface

The above two methods are to register mappers one by one. If we write a lot of mappers, can we register in batches?

Mybatis provides a way to register scan packages in batches. The following configuration needs to be added to the mybatis global configuration file:

<mappers>
    <package name="需要扫描的包" />
</mappers>

Mybatis will scan all interfaces in the package and sub-packages specified by the name attribute in the package element, and register it as a Mapper interface, so generally we will create a mapper package with the Mapper interface and the Mapper xml file of the same name.

Use attention

Method 3 will scan all interfaces in the specified package and register these interfaces as Mapper interfaces. As long as the scanned type is an interface, it will be registered. Therefore, we usually only put the Mapper interface in the specified package to avoid storing some irrelevant Class or interface.

About configuration and source code

Some of the configurations explained this time are configured in the mybatis global configuration file. The configuration of these elements is in order. The specific elements are defined in the following dtd file:

http://mybatis.org/dtd/mybatis-3-config.dtd

I suggest you take a look at this dtd configuration file.

to sum up

  1. Master the 3 ways of alias registration, it is recommended that you use custom aliases as little as possible
  2. Master 3 ways of attribute configuration
  3. Master the 3 ways of mapper registration and the points to pay attention to

At last

  • If you feel that you are rewarded after reading it, I hope to pay attention to it. By the way, give me a thumbs up. This will be the biggest motivation for my update. Thank you for your support.
  • Welcome everyone to pay attention to my public account [Java Fox], focusing on the basic knowledge of java and computer, I promise to let you get something after reading it, if you don’t believe me, hit me
  • Seek one-click triple connection: like, forward, and watching.
  • If you have different opinions or suggestions after reading, please comment and share with us. Thank you for your support and love.

——I am Chuhu, and I love programming as much as you.

Welcome to follow the public account "Java Fox" for the latest news

Guess you like

Origin blog.csdn.net/issunmingzhi/article/details/113776783