Mybatis global configuration

There are many configurations, here is just to explain some of the more commonly used and important ones.

<?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">
<!-- mybatis的主配置文件 -->
<configuration>
    <properties resource="conf/db.properties"></properties>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!-- 配置环境 -->
    <environments default="mysql">
        <!-- 配置mysql的环境-->
        <environment id="mysql">
            <!-- 配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源(连接池) -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件
        如UserMapper.xml:
        <select id="findAll" resultType="com.domain.User">
            select id, username as name, password,user_age from user_table
        </select>
    -->
    <!-- mappers -->
    <mappers>
<!--        <mapper class="com.dao.UserDao"/>-->
<!--        <mapper resource="com/dao/UserDao.xml" />-->
        <!--   批量注册     -->
        <package name="com.dao"/>
    </mappers>
</configuration>

1, properties (attributes)

 

<properties resource="conf/db.properties"></properties> 

Properties generally introduce external configuration, and it is commonly used to introduce database configuration files, such as creating a db.properties file in the resources directory.

Attributes:

resource : Import resources under the classpath

url : the resource under the network path or disk path

as follows:

db.properties:

jdbc.driver=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://localhost:3306/user
jdbc.username=root 
jdbc.password=1234
<configuration>       
    <properties resource="db.properties"></properties >    
    <dataSource type="POOLED">             
         <property name="driver" value="${jdbc.driver}"/>            
         <property name="url" value="${jdbc.url}"/>             
         <property name="username" value="${jdbc.username}"/>            
         <property name="password" value="${jdbc.password}"/>  
    </dataSource>  
< /configuration>

 2、settings 

setting : used to set each setting item

             name : the name of the  setting item

             value : the value of the setting item

Such as: set camel case naming rule mapping

The meanings of various settings, the reference values ​​and default values ​​are as follows

Set name meaning Reference Defaults
cacheEnabled Globally enable or disable any caches that have been configured by all mappers in the configuration file true, false true
lazyLoadingEnabled Global switch for delayed loading. When turned on, all associated objects will be lazily loaded. In a specific relationship, fetchType the switch state of the item can be overridden by setting  attributes true, false false
aggressiveLazyLoading When enabled, any method call will load all the properties of the object. Otherwise, each attribute will be loaded on demand (reference  lazyLoadTriggerMethods) true, false false (The default value is true in 3.4.1 and earlier versions)
multipleResultSetsEnabled Whether to allow a single statement to return multiple result sets (requires driver support) true, false true
useColumnLabel Use column labels instead of column names. Different drivers have different performances in this regard. For details, please refer to the relevant driver documents or test the two different modes to observe the results of the drivers used. true, false true
useGeneratedKeys To allow JDBC to support automatic generation of primary keys, driver support is required. If set to true, this setting forces the use of automatically generated primary keys. Although some drivers cannot support them, they can still work normally (such as Derby) true, false false
autoMappingUnknownColumnBehavior Automatically map the specified target discovery Unknown column (or unknown attribute type) behavior; NONE: without any reaction; WARNING: Log output level must be set to remind log  WARN; FAILING: mapping fails (throws  SqlSessionException) NONE, WARNING, FAILING NONE
defaultExecutorType Configure the default actuator. SIMPLE is an ordinary executor; REUSE executor will reuse prepared statements; BATCH executor will reuse statements and perform batch updates SIMPLE, REUSE, BATCH SIMPLE
defaultStatementTimeout Set the timeout period, which determines the number of seconds the driver waits for a response from the database Any positive integer Not set (null)
defaultFetchSize Set a hint value for the driven result set fetch size (fetchSize). This parameter can only be overridden in query settings Any positive integer Not set (null)
defaultResultSetType Specifies a scroll strategy when omit it per statement settings. (Since: 3.5.2) FORWARD_ONLY, SCROLL_SENSITIVE, SCROLL_INSENSITIVE, DEFAULT(same behavior with ‘Not Set’) Not Set
safeRowBoundsEnabled 允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为 false true, false false
safeResultHandlerEnabled 允许在嵌套语句中使用分页(ResultHandler)。如果允许使用则设置为 false true, false true
mapUnderscoreToCamelCase 是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射 true, false false
localCacheScope MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。 默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据 SESSION, STATEMENT SESSION
jdbcTypeForNull 当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。 某些驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER JdbcType 常量,常用值:NULL, VARCHAR 或 OTHER OTHER
lazyLoadTriggerMethods 指定哪个对象的方法触发一次延迟加载 用逗号分隔的方法列表 equals,clone,hashCode,toString
defaultScriptingLanguage 指定动态 SQL 生成的默认语言 一个类型别名或完全限定类名 org.apache.ibatis.scripting.xmltags.XMLLanguageDriver
defaultEnumTypeHandler 指定 Enum 使用的默认 TypeHandler 。(新增于 3.4.5) 一个类型别名或完全限定类名 org.apache.ibatis.type.EnumTypeHandler
callSettersOnNulls 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这在依赖于 Map.keySet() 或 null 值初始化的时候比较有用。注意基本类型(int、boolean 等)是不能设置成 null 的 true, false false
returnInstanceForEmptyRow 当返回行的所有列都是空时,MyBatis默认返回 null。 当开启这个设置时,MyBatis会返回一个空实例。 请注意,它也适用于嵌套的结果集 (如集合或关联)。(新增于 3.4.2) true, false false
logPrefix 指定 MyBatis 增加到日志名称的前缀 任何字符串 未设置
logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找 SLF4J, LOG4J, LOG4J2, JDK_LOGGING, COMMONS_LOGGING, STDOUT_LOGGING, NO_LOGGING 未设置
proxyFactory 指定 Mybatis 创建具有延迟加载能力的对象所用到的代理工具 CGLIB, JAVASSIST JAVASSIST (MyBatis 3.3 以上)
vfsImpl 指定 VFS 的实现 自定义 VFS 的实现的类全限定名,以逗号分隔 未设置
useActualParamName 允许使用方法签名中的名称作为语句参数名称。 为了使用该特性,你的项目必须采用 Java 8 编译,并且加上 -parameters 选项。(新增于 3.4.1) true, false true
configurationFactory 指定一个提供 Configuration 实例的类。 这个被返回的 Configuration 实例用来加载被反序列化对象的延迟加载属性值。 这个类必须包含一个签名为static Configuration getConfiguration() 的方法。(新增于 3.2.3) 类型别名或者全类名 未设置

3、typeAliases(类型别名) 

Mybatis 支持的默认别名,也可以采用自定义别名方式来开发。 

typeAliases别名处理器,可以为我们的Java类型取别名

alias:指定新的别名

type:指定要取别名的Java全类名称,默认别名是类名小写,例如:com.domain.User

typeAlias为某个Java类型取别名

别名不区分大小写。。。

<typeAlias alias="user" type="com.Ycy.domain.User"/> 

<configuration>       
    <properties resource="db.properties"></properties >   
    <typeAlias alias="user" type="com.Ycy.domain.User"/>  
    <dataSource type="POOLED">             
         <property name="driver" value="${jdbc.driver}"/>            
         <property name="url" value="${jdbc.url}"/>             
         <property name="username" value="${jdbc.username}"/>            
         <property name="password" value="${jdbc.password}"/>  
    </dataSource>  
</configuration>

Packahe:为某个包的所有类,批量取别名 

name:指定报名(为当前包以及下面的子包的每一个类都取一个别名(默认是类名小写)

例如:<package name="com.Ycy.domain"/> 

上面对com.Ycy.domain.User取别名user,这样只是对单个类取别名 ,对于许多的话,枚举显得非常麻烦,下面可以批量对对象进行取别名。

<configuration>       
    <properties resource="db.properties"></properties >   
    <typeAliases>  
    <package name="com.Ycy.domain"/>  
    <package name=" 其它包 "/> 
</typeAliases>  
    <dataSource type="POOLED">             
         <property name="driver" value="${jdbc.driver}"/>            
         <property name="url" value="${jdbc.url}"/>             
         <property name="username" value="${jdbc.username}"/>            
         <property name="password" value="${jdbc.password}"/>  
    </dataSource>  
</configuration>

 别名的首字母大写小写都无所谓,都可以的。

4、environments

environments:环境集合,mybatis可以配置多种环境,default指定使用某种环境。可以随时切换环境

environment:配置一个具体的环境信息,必须有两个标签,transactionManagerdataSource ,其中environment的id:代表当前环境的唯一标识

transactionManager:事务管理器

            type:事务管理器的类型,有两种事务管理器,一个是JDBC还一个是MANAGED

dataSource:数据源

           type:数据源类型;POOLED  UNPOOLED  JNDI(POOLED使用连接池技术)

<environments default="mysql">
        <!-- 配置mysql的环境-->
        <environment id="mysql">
            <!-- 配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源(连接池) -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
</environments>

5、mappers(映射器) 

mappers将sql映射注册到全局配置中

mapper:注册一个sql映射

mapper的属性

resource:引用类路径下的sql映射文件

<mapper resource="com/Ycy/dao/IUserDao.xml" />

url:引用网络路径或者磁盘上的sql映射文件

<mapper url="file:///com/Ycy/dao/IUserDao.xml" />

class:引用(注册)接口

       1、有sql映射文件,映射文件名必须和接口同名 ,并且返在与接口同一目录下

在这里会出现找不到xml文件的错误,把xxx.xml文件移动到接口包下,找不到xml文件,需要在pom.xml文件加入:

Exception in thread "main" org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.dao.UserDao.findAll

    <!--打包时打包mapper.xml文件-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

 2、没有sql文件,所有的sql都是利用注解写在接口上

代码如下:

public interface UserDao {
    /**
     * 查询所有
     * @return
     */
    @Select(" select id, username as name, password,user_age from user_table")
    List<User> findAll();
}

3、 <package name=""/> 批量注册

       注册指定包下的所有 mapper 接口

      如:

    <mappers>
<!--        <mapper class="com.dao.UserDao"/>-->
<!--        <mapper resource="com/dao/UserDao.xml" />-->
        <package name="com.dao"/>
    </mappers>

注意:此种方法要求 mapper 接口名称和 mapper 映射文件名称相同,且放在同一个目录中。 在实际开发中多使用这种方式。

Guess you like

Origin blog.csdn.net/weixin_43725517/article/details/108923490