[2] Detailed explanation of Mybatis core configuration files mybatis-config.xml and mapper.xml

4. Configuration analysis

1. Core configuration file

  • mybatis-config.xml system core configuration file

  • The configuration file of MyBatis contains settings and attribute information that will deeply affect the behavior of MyBatis.

  • The content that can be configured is as follows:

    configuration(配置)
    properties(属性)
    settings(设置)
    typeAliases(类型别名)
    typeHandlers(类型处理器)
    objectFactory(对象工厂)
    plugins(插件)
    environments(环境配置)
    environment(环境变量)
    transactionManager(事务管理器)
    dataSource(数据源)
    databaseIdProvider(数据库厂商标识)
    mappers(映射器)
    <!-- 注意元素节点的顺序!顺序不对会报错 -->
    

2. Environment configuration

<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>
  • Configure multiple operating environments of MyBatis, map SQL to multiple different databases, and one of them must be designated as the default operating environment (specified by default)

  • Child element node: environment

    • The dataSource element uses the standard JDBC data source interface to configure the resources of the JDBC connection object.

    • The data source must be configured.

    • There are three types of built-in data sources

      type="[UNPOOLED|POOLED|JNDI]")
      
    • unpooled: The implementation of this data source just opens and closes the connection each time it is requested.

    • pooled : The realization of this data source uses the concept of "pooling" to organize JDBC connection objects, which is a popular processing method that allows concurrent Web applications to respond quickly to requests.

    • jndi: This data source is implemented to be used in containers such as Spring or application servers. The container can configure the data source centrally or externally, and then place a reference to the JNDI context.

    • There are also many third-party implementations of data sources, such as dbcp, c3p0, druid, etc...

    • Details: Click to view official documents

    • Neither transaction manager type requires any properties to be set.

    • A specific set of environments is distinguished by setting id, id is guaranteed to be unique!

    • Child element node: transactionManager-[Transaction Manager]

      <!-- 语法 -->
      <transactionManager type="[ JDBC | MANAGED ]"/>
      
    • Child element node: data source (dataSource)

3. Properties

The configuration file can be referenced through the properties property

These properties are externally configurable and dynamically replaceable. They can be configured in a typical java file [db.properties], or can be passed in the sub-elements of the properties element.

Insert picture description here

The db.properties file:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/bigdata?userSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=root

Introduce directly in the core configuration file:

	<environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/bigdata?userSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
  • Can import external files directly
  • You can add some attribute configuration
  • If two files have the same field, the external configuration file is preferred

4. Type aliases (typeAliases)

  • Type aliases 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.

Give the entity class an alias:

	<typeAliases>
        <!--<package name="com.kuber.pojo"/>-->
        <typeAlias type="com.kuber.pojo.User" alias="User"/>
    </typeAliases>

You can also specify a package name, mybatis will search for the required Java Bean under the package name (scan the package of this entity class, its default alias is this class name, the first letter is lowercase (in fact, uppercase and lowercase are OK, just use the class name) )):

    <!--类型别名-->
    <typeAliases>
        <package name="com.kuber.pojo"/>
    </typeAliases>

When there are fewer entity classes, use the first method;

If there are a lot of entity classes, you can use the second one. I will use the second one from now on.

The first type can be DIY aliases, the second type cannot. If you use the second type and must change it, you need to add annotations to the entity class (Note: It is based on the second method! And you need to open the annotation scanning, I Let’s use the second one for now)

@Alias("nihaoa")
public class User {
    
    }

Here are some built-in type aliases for common Java types. They are all case-insensitive. Note that in order to cope with the naming duplication of the original type, a special naming style is adopted. (Official form)

Alias Type of mapping
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal
object Object
map Map
hashmap HashMap
list List
arraylist ArrayList
collection Collection
iterator Iterator

5. Settings

Set name description Effective value Defaults
cacheEnabled Globally enable or disable any cache configured in all mapper configuration files. true | false true
lazyLoadingEnabled Global switch for delayed loading. When enabled, all associated objects will be lazily loaded. In particular by setting the relationship fetchTypeto cover the switching state properties. true | false false
logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING 未设置

6、其他配置(先做了解)

  • 类型处理器(typeHandlers)

  • 对象工厂(objectFactory)

  • 插件(plugins)

    • MyBatis Generator Core
    • MyBatis Plus
    • 通用mapper

7、映射器(mappers)

MapperRegistry

  • 既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要来定义 SQL 映射语句了。

  • 但首先,我们需要告诉 MyBatis 到哪里去找到这些语句。

  • 在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。

  • 你可以使用相对于类路径的资源引用,或完全限定资源定位符(包括 file:/// 形式的 URL),或类名和包名等

方式一:我暂时都使用这种

    <!--每一个mapper.xml都需要在mybatis核心配置文件中进行注册,进行映射-->
    <mappers>
        <mapper resource="com/kuber/dao/UserMapper.xml"/>
    </mappers>

方式二:使用class文件绑定注册

    <mappers>
        <mapper class="com.kuber.dao.UserMapper"/>
    </mappers>

注意:

  • 接口和他的mapper.xml配置文件必须同名
  • 接口和他的mapper.xml配置文件必须在同一个包下

方式三:使用扫描包进行注入绑定

    <mappers>
        <package name="com.kuber.dao"/>
    </mappers>

注意:

  • 接口和他的mapper.xml配置文件必须同名
  • 接口和他的mapper.xml配置文件必须在同一个

8、生命周期

Insert picture description here

生命周期,和作用域,是至关重要的,因为错误的使用会导致非常严重的并发问题

SqlSessionFactoryBuilder

  • 这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。
  • 局部变量

SqlSessionFactory

  • 说白了就是可以想象为:数据库连接池
  • Once the SqlSessionFactory is created, it should always exist during the running of the application. There is no reason to discard it or re-create another instance.
  • Therefore, the best scope of SqlSessionFactory is the application scope.
  • The simplest is to use singleton mode and 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 request or method scope.

  • This close operation is very important. In order to ensure that the close operation can be executed every time, you should put this close operation in the finally block.

  • It needs to be closed immediately after use up, otherwise the resources will be occupied

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43215322/article/details/109546247