mybatis精讲(三)--标签及TypeHandler使用

4,851 阅读6分钟

[TOC]

话引

  • 前两张我们分别介绍了Mybatis环境搭建及其组件的生命周期。这些都是我们Mybatis入门必备技能。有了前两篇的铺垫我们今天就来深入下Mybatis, 也为了填下之前埋下的坑。

XML配置标签

概览


<?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=""/>
    <!--设置-->
    <settings/>
    <!--定义别名-->
    <typeAliases>
        <package name=""/>
    </typeAliases>
    <!--类型处理器-->
    <typeHandlers/>
    <!--对象工厂-->
    <objectFactory/>
    <!--插件-->
    <plugins/>
    <!--定义数据库信息,默认使用development数据库构建环境-->
    <environments default="development">
        <environment id="development">
            <!--jdbc事物管理-->
            <transactionManager type="JDBC"/>
            <!--配置数据库连接信息-->
            <dataSource type="POOLED"/>
        </environment>
    </environments>
    <!--数据库厂商标识-->
    <databaseIdProvider/>
    <mappers/>
</configuration>

  • 上面模板列出了所有xml可以配置的属性。这里plugins是一个让人哭笑不得的东西。用的好是利器,用的不好就是埋坑。接下来我们来看看各个属性的作用

properties

  • 该标签的作用就是引入变量。和maven的properties一样。在这里定义的变量或者引入的变量,在下面我们是可以童工${}使用的。

子标签property


<properties>
  <property name="zxhtom" value="jdbc:mysql://localhost:3306/mybatis"/>
</properties>

<dataSource type="POOLED">
<property name="driver" value="${zxhtom}"/>
<dataSource>

  • 上述的配置就可以直接使用zxhtom这个变量。

resource

  • 除了上述方法我们还可以通过引入其他properties文件,就可以使用文件里的配置变量了。

程序注入

  • 最后还有一种我们在构建SqlSessionFactory的时候重新载入我们的Properties对象就可以了。另外三者的优先级是从低到高

settings


configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));
configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));
configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler")));
configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));
configuration.setLogPrefix(props.getProperty("logPrefix"));
configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));

  • 上面代码是我们在XMLConfigBuilder解析settings标签的代码。从这段代码中我们了解到settings子标签。

别名

  • 别名是mybatis为我们项目中类起的一个名字,类名往往会很长所以别名就方便我们平时的开发。Mybatis为我们内置了一些类的别名:byte、short、int、long、float、double、boolean、char等基础类型的别名。还有其的封装类型、String,Object,Map,List等等常用的类。
    org.apache.ibatis.type.TypeAliasRegistry这个类中帮我们内置了别名。可以看下。自定义别名也是通过这个类进行注册的。我们可以通过settings中typeAliases配置的方式结合@Alias。或者扫描包也可以的。

TypeHandler

  • 这个接口就四个方法

public interface TypeHandler<T> {

  /**
   * 设置参数是用到的方法
   */
  void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException;

  T getResult(ResultSet rs, String columnName) throws SQLException;

  T getResult(ResultSet rs, int columnIndex) throws SQLException;

  T getResult(CallableStatement cs, int columnIndex) throws SQLException;

}

  • 可以理解成拦截器。它主要拦截的是设置参数和获取结果的两个节点。这个类的作用就是将Java对象和jdbcType进行相互转换的一个功能。同样的在org.apache.ibatis.type.TypeHandlerRegistry这个类中mybatis为我们提供了内置的TypeHandler。基本上是对于基本数据和分装对象的转换。
  • 下面我们随便看一个TypeHandler处理细节
public class BooleanTypeHandler extends BaseTypeHandler<Boolean> {

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType)
      throws SQLException {
    ps.setBoolean(i, parameter);
  }

  @Override
  public Boolean getNullableResult(ResultSet rs, String columnName)
      throws SQLException {
    boolean result = rs.getBoolean(columnName);
    return !result && rs.wasNull() ? null : result;
  }

  @Override
  public Boolean getNullableResult(ResultSet rs, int columnIndex)
      throws SQLException {
    boolean result = rs.getBoolean(columnIndex);
    return !result && rs.wasNull() ? null : result;
  }

  @Override
  public Boolean getNullableResult(CallableStatement cs, int columnIndex)
      throws SQLException {
    boolean result = cs.getBoolean(columnIndex);
    return !result && cs.wasNull() ? null : result;
  }
}

  • setParameter是PreparedStatement进行设置成boolean类型。getResult分别通过三种不同方式获取。在这些方法里我们可以根据自己也无需求进行控制。常见的控制是枚举的转换。传递参数过程可能是枚举的name,但是传递到数据库中要枚举的index.这种需求我们就可以在TypeHandler中实现。我们书写的typeHandler之后并不能被识别,还需要我们在resultMap中的result标签中通过typeHandler指定我们的自定义Handler.

自定义TypeHandler

  • 承接上文我们说道枚举的转换。下面我们还是已学生类为例。学生中性别之前是boolean类型。现在我们采用枚举类型。但是数据库中存的还是数据,01.

EnumTypeHandler

  • 在TypeHandlerRegister类中申明了默认的枚举类处理器是private Class defaultEnumTypeHandler = EnumTypeHandler.class;
@Override
public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
  String s = rs.getString(columnName);
  return s == null ? null : Enum.valueOf(type, s);
}
  • 我们通过这个方法可以看出,这个枚举处理器适合已枚举名称存储的方式


EnumOrdinalTypeHandler

  • 在Enum中还有一个属性oridinal。这个表示枚举中的索引。然后我们通过查看Mybatis提供的处理器发现有个叫EnumOrdinalTypeHandler。我们很容易联想到的就是这个处理器是通过枚举的所以作为数据库内容的。在SexEnum中MALE存储到数据库中则为0.注意这个0不是我们的index.而是MALE的索引。如果将MALE和FEMAEL调换。那么MALE索引则为1.
  • 因为默认的是EnumTypeHandler。所以想用EnumOrdinalTypeHandler的话我们要么在resultMap中sex字段指定该处理器。要不就通过配置文件typeHandlers注册进来。(将处理器与Java类进行绑定。mybatis遇到这个Java对象的时候就知道用什么处理器处理)

<typeHandlers>
    <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="com.github.zxhtom.enums.SexEnum"/>
</typeHandlers>

SexTypeHandler

  • 上面的不管是通过名称存储还是通过索引存储都不太满足我们的需求。我们想通过我们的index存储。那么这时候我们就得自定义处理逻辑了。Mybatis处理器都是继承BaseTypeHandler。因为BaseTypeHandler实现了TypeHandler.所以我们这里也就继承BaseTypeHandler。

public class SexTypeHandler extends BaseTypeHandler<SexEnum> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, SexEnum parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i,parameter.getIndex());
    }

    @Override
    public SexEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int i = rs.getInt(columnName);
        return SexEnum.getSexEnum(i);
    }

    @Override
    public SexEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int i = rs.getInt(columnIndex);
        return SexEnum.getSexEnum(i);
    }

    @Override
    public SexEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int i = cs.getInt(columnIndex);
        return SexEnum.getSexEnum(i);
    }
}

typeHandler注意点

  • 在编写自定义处理器的时候我们得之处Javatype、jdbctype。两者不是必填。但至少得有一个。正常我们默认javatype是必填的。
  • 填写的方式有三种
    • 通过MappedTypes、MappedJdbcTypes分别指定javatype、jdbctype
    • 通过在mybatis-config.xml中配置typeHandlers进行注解。里面也有这两个属性的配置。
    • 通过在mapper.xml的resultmap中再次指定某个字段的typehandler.
  • TypeHandler为我们提供了Java到jdbc数据的转换桥梁。极大的方便了我们平时的开发。让我们开发期间忽略数据的转换这么糟心的事情。

加入战队

加入战队

微信公众号

微信公众号