iis服务器助手广告广告
返回顶部
首页 > 资讯 > 数据库 >Mybatis的核心配置文件
  • 101
分享到

Mybatis的核心配置文件

mybatisjavamysql 2023-09-06 07:09:05 101人浏览 独家记忆
摘要

mybatis的核心配置文件有两个,一个是全局配置文件,它包含了会深深影响Mybatis行为的设置和属性信息;一个是映射文件,它很简单,让用户能更专注于sql代码。 全局配置文件 全局配置文件的顶层结

mybatis的核心配置文件有两个,一个是全局配置文件,它包含了会深深影响Mybatis行为的设置和属性信息;一个是映射文件,它很简单,让用户能更专注于sql代码。

全局配置文件

全局配置文件的顶层结构如下:
在这里插入图片描述

1.1 configuration(配置)

configuration 是整个配置文件的根标签。对应着Mybatis里最重要的配置类Configuration。这个类中的很多属性都和全局配置文件中的子标签对应。

public class Configuration {    protected Environment environment;    protected boolean safeRowBoundsEnabled;    protected boolean safeResultHandlerEnabled;    protected boolean mapUnderscoreToCamelCase;    protected boolean aggressiveLazyLoading;    protected boolean multipleResultSetsEnabled;    protected boolean useGeneratedKeys;    protected boolean useColumnLabel;    protected boolean cacheEnabled;    protected boolean callSettersOnNulls;    protected boolean useActualParamName;    protected boolean returnInstanceForEmptyRow;    protected String logPrefix;    protected Class<? extends Log> logImpl;    protected Class<? extends VFS> vfsImpl;    protected LocalCacheScope localCacheScope;    protected JdbcType jdbcTypeForNull;    protected Set<String> lazyLoadTriggerMethods;    protected Integer defaultStatementTimeout;    protected Integer defaultFetchSize;    protected ResultSetType defaultResultSetType;    protected ExecutorType defaultExecutorType;    protected AutoMappingBehavior autoMappingBehavior;    protected AutoMappingUnknownColumnBehavior autoMappingUnknownColumnBehavior;    protected Properties variables;    protected ReflectorFactory reflectorFactory;    protected ObjectFactory objectFactory;    protected ObjectWrapperFactory objectWrapperFactory;    protected boolean lazyLoadingEnabled;    protected ProxyFactory proxyFactory;    protected String databaseId;    protected Class<?> configurationFactory;    protected final MapperReGIStry mapperRegistry;    protected final InterceptorChain interceptorChain;    protected final TypeHandlerRegistry typeHandlerRegistry;    protected final TypeAliasRegistry typeAliasRegistry;    protected final LanguageDriverRegistry languageRegistry;    protected final Map<String, MappedStatement> mappedStatements;    protected final Map<String, Cache> caches;    protected final Map<String, ResultMap> resultMaps;    protected final Map<String, ParameterMap> parameterMaps;    protected final Map<String, KeyGenerator> keyGenerators;    protected final Set<String> loadedResources;    protected final Map<String, Xnode> sqlFragments;    protected final Collection<XMLStatementBuilder> incompleteStatements;    protected final Collection<CacheRefResolver> incompleteCacheRefs;    protected final Collection<ResultMapResolver> incompleteResultMaps;    protected final Collection<MethodResolver> incompleteMethods;    protected final Map<String, String> cacheRefMap;

1.2 properties(属性)

properties标签用来配置参数信息。
为了更加灵活的配置参数,我们把它们放在单独的properties中,用properties标签引入。
这样在xml文件中使用${} 就可以获取到。

属性文件:db.properties:

driver=com.Mysql.cj.jdbc.Driverurl=jdbc:mysql:///tool?useUnicode=true&characterEncoding=utf8username=rootpassWord=root

配置文件:mybatis-config.xml:

DOCTYPE configuration        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        "https://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <properties resource="db.properties">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="mapper/DeviceMapper.xml"/>    mappers>configuration>

1.3 settings(设置)

这是Mybatis中极为重要的调整配置,它们会改变Mybatis的运行时行为。
一个完整的settings元素示例如下:

<settings>  <setting name="cacheEnabled" value="true"/>   <setting name="lazyLoadingEnabled" value="true"/>  <setting name="aggressiveLazyLoading" value="true"/>  <setting name="multipleResultSetsEnabled" value="true"/>  <setting name="useColumnLabel" value="true"/>  <setting name="useGeneratedKeys" value="false"/>  <setting name="autoMappingBehavior" value="PARTIAL"/>  <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>  <setting name="defaultExecutorType" value="SIMPLE"/>  <setting name="defaultStatementTimeout" value="25"/>  <setting name="defaultFetchSize" value="100"/>  <setting name="safeRowBoundsEnabled" value="false"/>  <setting name="safeResultHandlerEnabled" value="true"/>  <setting name="mapUnderscoreToCamelCase" value="false"/>  <setting name="localCacheScope" value="SESSION"/>  <setting name="jdbcTypeForNull" value="OTHER"/>  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>  <setting name="defaultScriptingLanguage" value="org.apache.ibatis.scripting.xmltags.XMLLanguageDriver"/>  <setting name="defaultEnumTypeHandler" value="org.apache.ibatis.type.EnumTypeHandler"/>  <setting name="callSettersOnNulls" value="false"/>  <setting name="returnInstanceForEmptyRow" value="false"/>  <setting name="logPrefix" value="exampleLogPreFix_"/>  <setting name="logImpl" value="SLF4J | LOG4J | LOG4J2 | jdk_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING"/>  <setting name="proxyFactory" value="CGLIB | JAVASSIST"/>  <setting name="vfsImpl" value="org.mybatis.example.YourselfVfsImpl"/>  <setting name="useActualParamName" value="true"/>  <setting name="configurationFactory" value="org.mybatis.example.ConfigurationFactory"/>settings>

1.4 typeAlisaes(类型别名)

类型别名可以为java类型设置一个缩写名字,主要用来简化全类名的书写。
我们可以为单个类指定别名,如:

   <typeAliases>        <typeAlias type="com.lk.tool.bean.Device" alias="Device"/>    typeAliases>

我们也可以指定一个包名,将包下所有的Bean都以首字母小写的名称来做别名。

    <typeAliases>        <package name="com.lk.tool.bean"/>    typeAliases>

如上所示,com.lk.tool.bean.Device的别名为 device。若类上有注解,别名为其注解值。如下所示:

@Alias("device")public class Device{    ...}

MyBatis中有一些预置好的类型别名,在TypeAliasRegistry中。

public TypeAliasRegistry() {        this.registerAlias("string", String.class);        this.registerAlias("byte", Byte.class);        this.registerAlias("long", Long.class);        this.registerAlias("short", Short.class);        this.registerAlias("int", Integer.class);        this.registerAlias("integer", Integer.class);        this.registerAlias("double", Double.class);        this.registerAlias("float", Float.class);        this.registerAlias("boolean", Boolean.class);        this.registerAlias("byte[]", Byte[].class);        this.registerAlias("long[]", Long[].class);        this.registerAlias("short[]", Short[].class);        this.registerAlias("int[]", Integer[].class);        this.registerAlias("integer[]", Integer[].class);        this.registerAlias("double[]", Double[].class);        this.registerAlias("float[]", Float[].class);        this.registerAlias("boolean[]", Boolean[].class);        this.registerAlias("_byte", Byte.TYPE);        this.registerAlias("_long", Long.TYPE);        this.registerAlias("_short", Short.TYPE);        this.registerAlias("_int", Integer.TYPE);        this.registerAlias("_integer", Integer.TYPE);        this.registerAlias("_double", Double.TYPE);        this.registerAlias("_float", Float.TYPE);        this.registerAlias("_boolean", Boolean.TYPE);        this.registerAlias("_byte[]", byte[].class);        this.registerAlias("_long[]", long[].class);        this.registerAlias("_short[]", short[].class);        this.registerAlias("_int[]", int[].class);        this.registerAlias("_integer[]", int[].class);        this.registerAlias("_double[]", double[].class);        this.registerAlias("_float[]", float[].class);        this.registerAlias("_boolean[]", boolean[].class);        this.registerAlias("date", Date.class);        this.registerAlias("decimal", BigDecimal.class);        this.registerAlias("bigdecimal", BigDecimal.class);        this.registerAlias("biginteger", BigInteger.class);        this.registerAlias("object", Object.class);        this.registerAlias("date[]", Date[].class);        this.registerAlias("decimal[]", BigDecimal[].class);        this.registerAlias("bigdecimal[]", BigDecimal[].class);        this.registerAlias("biginteger[]", BigInteger[].class);        this.registerAlias("object[]", Object[].class);        this.registerAlias("map", Map.class);        this.registerAlias("HashMap", HashMap.class);        this.registerAlias("list", List.class);        this.registerAlias("arraylist", ArrayList.class);        this.registerAlias("collection", Collection.class);        this.registerAlias("iterator", Iterator.class);        this.registerAlias("ResultSet", ResultSet.class);    }

其中就有熟悉的 string、date、map。

1.5 typeHandler(类型处理器)

MyBatis在设置预处理语句(PreparedStatement)中的参数或从结果集中取出一个值时,都会用类型处理器将获取到的值以合适的方式转换成Java类型。
由于Java类型和数据库的JDBC类型存在差异,并非万千对应,所以类型处理器的作用很必要。比如 String 与 Varchar、text。
由于MyBatis内置了很多TypeHandler,都注册在TypeHandlerRegistry中,所以当我们查询数据或者插入数据时,不需要特别处理就可以做数据转换,因为它们自动调用了对应的TypeHandler方法。
我们可以重写已有的类型处理器或创建自己的类型处理器,来处理不支持的或非标准的类型。
具体做法为:实现 org.apache.ibatis.type.TypeHandler 接口, 或继承一个很便利的类 org.apache.ibatis.type.BaseTypeHandler, 并且可以(可选地)将它映射到一个 JDBC 类型。比如:我们针对card_no字段做一个特别处理,使用掩码将中间11位置*。
首先写一个自定义的StringTypeHandler类:

package com.lk.tool.typehandler;import com.alibaba.excel.util.StringUtils;import org.apache.ibatis.type.BaseTypeHandler;import org.apache.ibatis.type.JdbcType;import java.sql.*;public class StringTypeHandler extends BaseTypeHandler<String> {    @Override    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {        ps.setString(i,parameter);    }    @Override    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {        String obj = (String)rs.getObject(columnName);        System.out.println(obj);        if("card_no".equals(columnName) && StringUtils.isNotBlank(obj)){            StringBuffer buffer = new StringBuffer();            return buffer.append(obj.substring(0,6)).append("***********").append(obj.substring(17)).toString();        }        return rs.getString(columnName);    }    @Override    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {        return rs.getString(columnIndex);    }    @Override    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {        return cs.getString(columnIndex);    }}

在全局配置文件 mybatis-config.xml中增加如下配置项:

    <typeHandlers>        <typeHandler handler="com.lk.tool.typehandler.StringTypeHandler">typeHandler>    typeHandlers>

即可实现掩码功能:(输出查询结果)

Device(id=2, sn=2234567, cardNo=120223***********4)

1.6 objectFactory(对象工厂)

每次MyBatis 创建结果对象的新实例时,它都会使用一个对象工厂(ObjectFactory)实例来完成实例化工作。默认的对象工厂需要做的仅仅是实例化目标类,要么通过默认无参构造方法,要么通过存在的参数映射来调用带有参数的构造方法。
如果想覆盖对象工厂的默认行为,可以通过创建自己的对象工厂来实现。例如:

// ExampleObjectFactory.javapublic class ExampleObjectFactory extends DefaultObjectFactory {  @Override  public <T> T create(Class<T> type) {    return super.create(type);  }  @Override  public <T> T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {    return super.create(type, constructorArgTypes, constructorArgs);  }  @Override  public void setProperties(Properties properties) {    super.setProperties(properties);  }  @Override  public <T> boolean isCollection(Class<T> type) {    return Collection.class.isAssignableFrom(type);  }}
<objectFactory type="org.mybatis.example.ExampleObjectFactory">  <property name="someProperty" value="100"/>objectFactory>

ObjectFactory 接口很简单,包含两个创建实例用的方法,一个是处理默认无构造方法的,另外一个是处理带参数的构造方法的。另外 setProperties 方法可以被用来配置ObjectFactory,在初始化你的ObjectFactory实例后,objectFactory元素体中定义的属性会被传递给 setProperties 方法。

1.7 plugins(插件

MyBatis允许我们在映射语句执行过程中的某一点进行拦截调用。
默认情况下,MyBatis允许使用插件来拦截的方法调用包括:

Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
ParameterHandler (getParameterObject, setParameters)
ResultSetHandler (handleResultSets, handleOutputParameters)
StatementHandler (prepare, parameterize, batch, update, query)
这些类中方法的细节可以通过查看每个方法的签名来发现。
只需要实现Interceptor接口,并制定想要拦截的方法,即可使用插件。
如下示例,会拦截在Executor实例中所有的“update” 方法调用,这里的Executor是负责执行底层映射语句的内部对象。

// ExamplePlugin.java@Intercepts({@Signature(  type= Executor.class,  method = "update",  args = {MappedStatement.class,Object.class})})public class ExamplePlugin implements Interceptor {  private Properties properties = new Properties();  @Override  public Object intercept(Invocation invocation) throws Throwable {    // implement pre processing if need    Object returnObject = invocation.proceed();    // implement post processing if need    return returnObject;  }  @Override  public void setProperties(Properties properties) {    this.properties = properties;  }}
<plugins>  <plugin interceptor="org.mybatis.example.ExamplePlugin">    <property name="someProperty" value="100"/>  plugin>plugins>

1.8 environments(环境配置)

environment标签用来管理数据库的环境,比如我们可以有开发环境、测试环境、生产环境的数据库。可以在不同的环境中使用不同的数据库地址或类型。

<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>

envionment
一个environment标签就是一个数据源,代表一个数据库。这里有两个标签
○ transactionManager(事务管理器)
如果配置的是JDBC,则会使用Connection对象的commit()、rollback()、close()管理事务
如果配置成MANAGE,会把事务交给容器来管理,比如WEBlogic。如果我们跑的是本地服务,那么配置MANAGE不会有任务事务。
如果是spring + Mybatis,则不必配置。我们会直接在 applicationContext.xml里面配置数据源和事务,覆盖MyBatis的配置。
○ dataSource(数据源)
一个数据源就对应一个数据库。
一般数据源都包括连接池的管理功能,所以DataSource也经常被称为连接池,或者是带连接池功能的数据源。

1.9 mappers(映射器)

既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要来定义 SQL 映射语句了。
如下这些配置会告诉 MyBatis 去哪里找映射文件

<mappers>  <mapper resource="org/mybatis/builder/AuthORMapper.xml"/>  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>  <mapper resource="org/mybatis/builder/PostMapper.xml"/>mappers>
<mappers>  <mapper url="file:///var/mappers/AuthorMapper.xml"/>  <mapper url="file:///var/mappers/BlogMapper.xml"/>  <mapper url="file:///var/mappers/PostMapper.xml"/>mappers>
<mappers>  <mapper class="org.mybatis.builder.AuthorMapper"/>  <mapper class="org.mybatis.builder.BlogMapper"/>  <mapper class="org.mybatis.builder.PostMapper"/>mappers>
<mappers>  <package name="org.mybatis.builder"/>mappers>

关于映射文件的细节,我们下篇文章详细讨论。

来源地址:https://blog.csdn.net/yuiezt/article/details/128826039

您可能感兴趣的文档:

--结束END--

本文标题: Mybatis的核心配置文件

本文链接: https://www.lsjlt.com/news/396666.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • sql怎么查看表的索引
    通过查询系统表,可以获取表的索引信息,包括索引名称、是否唯一、索引类型、索引列和行数。常用系统表有:mysql 的 information_schema.statistics、postg...
    99+
    2024-05-14
    mysql oracle
  • sql怎么查看索引
    您可以使用 sql 通过以下方法查看索引:show indexes 语句:显示表中定义的索引列表及其信息。explain 语句:显示查询计划,其中包含用于执行查询的索引。informat...
    99+
    2024-05-14
  • sql怎么查看存储过程
    如何查看 sql 存储过程的源代码:使用 show create procedure 语句直接获取创建脚本。查询 information_schema.routines 表的 routi...
    99+
    2024-05-14
  • sql怎么查看视图表
    要查看视图表,可以使用以下步骤:使用 select 语句获取视图中的数据。使用 desc 语句查看视图的架构。使用 explain 语句分析视图的执行计划。使用 dbms 提供...
    99+
    2024-05-14
    oracle python
  • sql怎么查看创建的视图
    可以通过sql查询查看已创建的视图,具体步骤包括:连接到数据库并执行查询select * from information_schema.views;查询结果将显示视图的名称、...
    99+
    2024-05-14
    mysql
  • sql怎么用循环语句实现查询
    可以通过 do 和 while 语句创建循环,并在循环内执行查询,详细步骤包括:定义循环变量设置循环初始值循环执行查询更新循环变量执行查询循环退出条件 SQL 中使用循环语句实现查询 ...
    99+
    2024-05-14
  • sql怎么用代码修改表中数据
    通过 sql 代码修改表中数据的方法包括:修改单个记录:使用 update 语句设置列值并指定条件。修改多条记录:在 update 语句中指定多个条件来修改满足条件的所有记录。增加新列:...
    99+
    2024-05-14
  • sql怎么用命令创建数据库
    在 sql 中使用 create database 命令创建新数据库,其语法包含以下步骤:指定数据库名称。指定数据库文件和日志文件的位置(可选)。指定数据库大小、最大大小和文件增长(可选...
    99+
    2024-05-14
  • sql怎么用身份证提取年龄
    sql 中提取身份证号码中的年龄的方法:提取出生日期部分(身份证号码中第 7-14 位);使用 to_date 函数转换为日期格式;使用 extract 函数计算与当前日期之间的年差。 ...
    99+
    2024-05-14
  • sql怎么看字段长度
    有两种方法可查看 sql 中的字段长度:使用 information_schema 架构,其中包含元数据信息,可用于查询字段长度。使用内建函数,如 length(),其适用于字符串数据类...
    99+
    2024-05-14
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作