Mybatis___ profile configuration to explain

The main configuration file

<?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">
<configuration>
    <!-- 引入外部资源 -->
    <properties resource="db.properties" />
    
    <!-- 自定义别名 -->
    <typeAliases>
        <typeAlias type="com.pojo.Emp" alias="emp"/>
        <typeAlias type="com.pojo.EmpA" alias="empA"/>
        <typeAlias type="com.pojo.GetEmp" alias="gEmp"/>
        <typeAlias type="com.pojo.Dept" alias="dept"/>
    </typeAliases>
    
    <!-- 类型处理器
    <typeHandlers>
        <typeHandler handler="com.typeHandler.ListtypeHandlers"/>
    </typeHandlers> -->
    
    <!-- 环境 -->
    <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="${user_name}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
    
    <!-- 映射器 -->
    <mappers>
        <!-- <mapper resource="com/mapper/IEmpDao.xml" /> -->
        <package name="com.mapper"/>
    </mappers>
</configuration>

1, the top-level structure of the document:

configuration 配置
    properties 属性
    settings 设置
    typeAliases 类型别名
    typeHandlers 类型处理器
    objectFactory 对象工厂
    plugins 插件
    environments 环境
    environment 环境变量
    transactionManager 事务管理器
    dataSource 数据源
    databaseIdProvider 数据库厂商标识
    mappers 映射器

2, properties
configure some common variables:
for example: the introduction of the database configuration

db. properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/demo?characterEncoding=utf8
user_name=xxx
password=xxx

3, setting
changes the runtime behavior of MyBatis

<settings>
  <!-- 全局地开启或关闭配置文件中的所有映射器已经配置的任何缓存。 -->
  <setting name="cacheEnabled" value="true"/>
 
 <!-- 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。
  特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态 --> 
  <setting name="lazyLoadingEnabled" value="true"/>
  
  <!-- 当开启时,任何方法的调用都会加载该对象的所有属性。
  否则,每个属性会按需加载(参考lazyLoadTriggerMethods). -->
   <setting name="aggressiveLazyLoading" value="true"/>
   
   <!-- 是否允许单一语句返回多结果集(需要兼容驱动)-->
  <setting name="multipleResultSetsEnabled" value="true"/>
  
  <!-- 使用列标签代替列名。不同的驱动在这方面会有不同的表现, 
  具体可参考相关驱动文档或通过测试这两种不同的模式来观察所用驱动的结果。 -->
  <setting name="useColumnLabel" value="true"/>
  
  <!-- 允许 JDBC 支持自动生成主键,需要驱动兼容。 
  如果设置为 true 则这个设置强制使用自动生成主键,
  尽管一些驱动不能兼容但仍可正常工作(比如 Derby)。 -->
  <setting name="useGeneratedKeys" value="false"/>
  
  <!--      
  指定 MyBatis 应如何自动映射列到字段或属性。 
  NONE 表示取消自动映射;PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。 
  FULL 会自动映射任意复杂的结果集(无论是否嵌套)。 -->
  <setting name="autoMappingBehavior" value="PARTIAL"/>
  
  <!-- 指定发现自动映射目标未知列(或者未知属性类型)的行为。 
  NONE: 不做任何反应WARNING: 输出提醒日志(‘org.apache.ibatis.session.AutoMappingUnknownColumnBehavior’ 的日志等级必须设置为 WARN) 
  FAILING: 映射失败 (抛出 SqlSessionException) -->
  <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
  
  <!-- 配置默认的执行器。
  SIMPLE 就是普通的执行器;
  REUSE 执行器会重用预处理语句(prepared statements);
  BATCH 执行器将重用语句并执行批量更新。 -->
  <setting name="defaultExecutorType" value="SIMPLE"/>
  
  <!-- 设置超时时间,它决定驱动等待数据库响应的秒数。 -->
  <setting name="defaultStatementTimeout" value="25"/>
  
  <!-- 为驱动的结果集获取数量(fetchSize)设置一个提示值。此参数只可以在查询设置中被覆盖。 -->
  <setting name="defaultFetchSize" value="100"/>
  
  <!-- 允许在嵌套语句中使用分页(RowBounds)。
  如果允许使用则设置为false。 -->
  <setting name="safeRowBoundsEnabled" value="false"/>
  
  <!-- 是否开启自动驼峰命名规则(camel case)映射,
  即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。 -->
  <setting name="mapUnderscoreToCamelCase" value="false"/>
  
  <!--MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。 
  默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。 
  若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。 -->
  <setting name="localCacheScope" value="SESSION"/>
  
  <!-- 当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。 
  某些驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。 -->
  <setting name="jdbcTypeForNull" value="OTHER"/>
  
  <!--      指定哪个对象的方法触发一次延迟加载。 -->
  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>

4、typeHandlers

类型别名是为 Java 类型设置一个短的名字。
它只和 XML 配置有关,
存在的意义仅在于用来减少类完全限定名的冗余
别名      映射的类型
_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

We can also customize Alias:

    <!-- 自定义别名 -->
    <typeAliases>
        <typeAlias type="com.pojo.Emp" alias="emp"/>
        <typeAlias type="com.pojo.EmpA" alias="empA"/>
        <typeAlias type="com.pojo.GetEmp" alias="gEmp"/>
        <typeAlias type="com.pojo.Dept" alias="dept"/>
    </typeAliases>

In the main configuration file is the alias, the alias can be used in the mapping file in place of the full path name of the class (alias name used when attention custom case insensitive)

5, typeHandlers (processor type)

实现Java类型和数据库类型之间转换的。
除了系统提供的类型转换器之外,开发者也可以自定义类型转换

Pojo in a list, a database is VARCHAR type:

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
public class ListtypeHandler extends BaseTypeHandler<List<String>>{

    @Override
    public List<String> getNullableResult(ResultSet rset, String str) throws SQLException {
        // TODO Auto-generated method stub
        return Arrays.asList(rset.getString(str).split(";"));
    }

    @Override
    public List<String> getNullableResult(ResultSet rset, int i) throws SQLException {
        // TODO Auto-generated method stub
        return Arrays.asList(rset.getString(i).split(";"));
    }

    @Override
    public List<String> getNullableResult(CallableStatement arg0, int arg1) throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement pre, int i, List<String> parem, JdbcType jdbc)
            throws SQLException {
        // TODO Auto-generated method stub
        StringBuilder builder = new StringBuilder();
        for (String string : parem) {
            builder.append(string+";");
        }
        
        if (builder != null) {
            builder.toString().substring(0, builder.length()-1);
            pre.setString(i, builder.toString());
        }
    }

    

}

sing:

test:

// 3.通过SqlSessionFactory对象获取SQLSession对象
            SqlSession session = MybatisUtils.getSqlSession();
            Emp emp = new Emp();
            emp.setEname("ename");

            List<String> list =new ArrayList<>();
            list.add("dnf");
            list.add("cs");
            list.add("cc");
            emp.setFavorites(list);
            //通过Java动态代理自动提供了IEmpDao的实现类
            IEmpDao mapper = session.getMapper(IEmpDao.class);
            int count = mapper.insEmp(emp);
            System.out.println("影响的行数:"+count);
            session.commit();

6, mapper (mapper)

将映射文件添加进主配置文件,将映射文件与主配置文件关联

Resource use to scan:

这种配置方式,对mapper的文件名没有要求
<!-- 映射器 -->
    <mappers>
        <mapper resource="com/mapper/IEmpDao.xml" /> 
        <!-- <package name="com.mapper"/>-->
    </mappers>

Scan using the package:

对mapper文件名有要求,要求mapper文件名和mapper接口必须一致。
<!-- 映射器 -->
    <mappers>
        <!-- <mapper resource="com/mapper/IEmpDao.xml" /> -->
        <package name="com.mapper"/>
    </mappers>

Guess you like

Origin www.cnblogs.com/zhangsonglin/p/10977496.html
Recommended