当前位置: 移动技术网 > IT编程>开发语言>Java > Mybatis结果集自动映射的实例代码

Mybatis结果集自动映射的实例代码

2019年07月22日  | 移动技术网IT编程  | 我要评论
在使用mybatis时,有的时候我们可以不用定义resultmap,而是直接在<select>语句上指定resulttype。这个时候其实就用到了mybatis

在使用mybatis时,有的时候我们可以不用定义resultmap,而是直接在<select>语句上指定resulttype。这个时候其实就用到了mybatis的结果集自动映射。mybatis的自动映射默认是开启的,有需要我们也可以将其关闭(还可以调整自动映射的策略)。

1       mybatis结果集自动映射 

       在使用mybatis时,有的时候我们可以不用定义resultmap,而是直接在<select>语句上指定resulttype。这个时候其实就用到了mybatis的结果集自动映射。mybatis的自动映射默认是开启的,其在映射的时候会先把没有在resultmap中定义字段映射的字段按照名称相同的方式自动映射到返回类型的对应属性上。自动映射的时候会忽略大小写,比如查询语句中查询出来了一个字段是id,我们对应的返回类型有一个属性id,且有一个setid()方法,那么id跟id也是可以匹配的,是可以自动映射的,mybatis就会把查询出来的结果集中字段id对应的值赋给返回类型对象的id属性。

1.1     源码分析

       关于自动映射这块的逻辑规则可以参考mybatis的defaultresultsethandler的源码,其核心代码如下。 

private boolean applyautomaticmappings(resultsetwrapper rsw, resultmap resultmap, metaobject metaobject, string columnprefix) throws sqlexception {
  list<unmappedcolumautomapping> automapping = createautomaticmappings(rsw, resultmap, metaobject, columnprefix);
  boolean foundvalues = false;
  if (automapping.size() > 0) {
   for (unmappedcolumautomapping mapping : automapping) {
    final object value = mapping.typehandler.getresult(rsw.getresultset(), mapping.column);
    if (value != null || configuration.iscallsettersonnulls()) {
     if (value != null || !mapping.primitive) {
      metaobject.setvalue(mapping.property, value);
     }
     foundvalues = true;
    }
   }
  }
  return foundvalues;
 }
 private list<unmappedcolumautomapping> createautomaticmappings(resultsetwrapper rsw, resultmap resultmap, metaobject metaobject, string columnprefix) throws sqlexception {
  final string mapkey = resultmap.getid() + ":" + columnprefix;
  list<unmappedcolumautomapping> automapping = automappingscache.get(mapkey);
  if (automapping == null) {
   automapping = new arraylist<unmappedcolumautomapping>();
   final list<string> unmappedcolumnnames = rsw.getunmappedcolumnnames(resultmap, columnprefix);
   for (string columnname : unmappedcolumnnames) {
    string propertyname = columnname;
    if (columnprefix != null && !columnprefix.isempty()) {
     if (columnname.touppercase(locale.english).startswith(columnprefix)) {
      propertyname = columnname.substring(columnprefix.length());
     } else {
      continue;
     }
    }
    final string property = metaobject.findproperty(propertyname, configuration.ismapunderscoretocamelcase());
    if (property != null && metaobject.hassetter(property)) {
     final class<?> propertytype = metaobject.getsettertype(property);
     if (typehandlerregistry.hastypehandler(propertytype)) {
      final typehandler<?> typehandler = rsw.gettypehandler(propertytype, columnname);
      automapping.add(new unmappedcolumautomapping(columnname, property, typehandler, propertytype.isprimitive()));
     }
    }
   }
   automappingscache.put(mapkey, automapping);
  }
  return automapping;
 } 

       在上面的源码中createautomaticmappings()方法中的下面这句就是获取当前查询结果集中没有在resultmap中映射的字段,以进行自动映射。详情请参考完整的源码。

 final list<string> unmappedcolumnnames = rsw.getunmappedcolumnnames(resultmap, columnprefix);

1.2     示例

       现假设我们有一个user类,其有id、name、username、email、mobile属性,然后有下面这样一个查询及其对应的resultmap定义。我们可以看到我们查询出来的有id、name、user_name、email和mobile字段,在resultmap中我们只配置了字段user_name对应的是username属性,其它的我们都没配置,但是查询出来的结果中user对象的id、name、username、email和mobile属性都会有值,因为它们会被mybatis以自动映射策略进行赋值。

 <resultmap type="com.elim.learn.mybatis.model.user" id="baseresult">
   <result column="user_name" property="username"/>
  </resultmap>
  <select id="findbyid" resultmap="baseresult" parametertype="java.lang.long" >
   select id,name,username user_name,email,mobile from t_user where id=#{id}
  </select>

1.3     自动映射策略

       mybatis的自动映射策略默认是开启的,而且默认是只对非嵌套的resultmap进行自动映射。这是通过mybatis的全局配置automappingbehavior参数配置的。它一共有三种取值,分别是none、partial和full。

l  none表示不启用自动映射

l  partial表示只对非嵌套的resultmap进行自动映射

l  full表示对所有的resultmap都进行自动映射

    <!-- 自动映射类型,可选值为none、partial和full,参考automappingbehavior枚举 -->
   <setting name="automappingbehavior" value="partial"/>

       除了全局的是否启用自动映射的配置外,还可以对特定的resultmap设置是否启用自动映射。这是通过resultmap的automapping属性配置的,可选值是true和false。定义在resultmap上的automapping的优先级比全局配置的优先级更高。

1.4     resulttype自动映射分析

       我们在指定一个查询语句的返回结果时,可以直接指定resulttype,也可以是指定resultmap,然后由指定的resultmap的type属性指定真实的返回类型。实际上,mybatis的底层在对结果集进行处理时都是通过resultmap进行处理的。当我们指定的是resulttype时,mybatis内部会生成一个空的resultmap,然后指定其对应的type为我们指定的resulttype类型。那这个时候之所以返回结果能自动映射到resulttype类型的对应属性上,就是上面介绍的mybatis的自动映射机制的作用。如果在这种情况下,我们把全局的自动映射关闭了,那么mybatis就不能自动映射了,也就得不到我们需要的返回结果了。如下就是直接指定的resulttype。

  <select id="findbyid" resulttype="com.elim.learn.mybatis.model.user" parametertype="java.lang.long" >
   select id,name,username,email,mobile from t_user where id=#{id}
  </select>

       mybatis的mapper.xml文件的内容是由xmlmapperbuilder解析的,而其中定义的mapper语句(select、insert等)则是由xmlstatementbuilder解析的,解析后会生成一个mappedstatement。对于select语句,其对应的resultmap的解析的核心逻辑如下,更多信息请参考官方源码。

private list<resultmap> getstatementresultmaps(
   string resultmap,
   class<?> resulttype,
   string statementid) {
  resultmap = applycurrentnamespace(resultmap, true);
  list<resultmap> resultmaps = new arraylist<resultmap>();
  if (resultmap != null) {
   string[] resultmapnames = resultmap.split(",");
   for (string resultmapname : resultmapnames) {
    try {
     resultmaps.add(configuration.getresultmap(resultmapname.trim()));
    } catch (illegalargumentexception e) {
     throw new incompleteelementexception("could not find result map " + resultmapname, e);
    }
   }
  } else if (resulttype != null) {
   resultmap inlineresultmap = new resultmap.builder(
     configuration,
     statementid + "-inline",
     resulttype,
     new arraylist<resultmapping>(),
     null).build();
   resultmaps.add(inlineresultmap);
  }
  return resultmaps;
 }

以上所述是小编给大家介绍的mybatis结果集自动映射的实例代码,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网