MyBatis的ResultMapping和ResultMap

CSDN LoveLion

复杂对象的组装与创建——建造者模式(一)

Effective java 第3版中描述的Builder模式

Java设计模式14:建造者模式

2个类都使用了Builder来构建对象。

ResultMapping

package org.apache.ibatis.mapping;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set; import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry; public class ResultMapping { private Configuration configuration;
private String property;
private String column;
private Class<?> javaType;
private JdbcType jdbcType;
private TypeHandler<?> typeHandler;
private String nestedResultMapId;
private String nestedQueryId;
private Set<String> notNullColumns;
private String columnPrefix;
private List<ResultFlag> flags;
private List<ResultMapping> composites;
private String resultSet;
private String foreignColumn;
private boolean lazy; ResultMapping() {
} public static class Builder {
private ResultMapping resultMapping = new ResultMapping(); public Builder(Configuration configuration, String property, String column, TypeHandler<?> typeHandler) {
this(configuration, property);
resultMapping.column = column;
resultMapping.typeHandler = typeHandler;
} public Builder(Configuration configuration, String property, String column, Class<?> javaType) {
this(configuration, property);
resultMapping.column = column;
resultMapping.javaType = javaType;
} public Builder(Configuration configuration, String property) {
resultMapping.configuration = configuration;
resultMapping.property = property;
resultMapping.flags = new ArrayList<>();
resultMapping.composites = new ArrayList<>();
resultMapping.lazy = configuration.isLazyLoadingEnabled();
} public Builder javaType(Class<?> javaType) {
resultMapping.javaType = javaType;
return this;
} public Builder jdbcType(JdbcType jdbcType) {
resultMapping.jdbcType = jdbcType;
return this;
} public Builder nestedResultMapId(String nestedResultMapId) {
resultMapping.nestedResultMapId = nestedResultMapId;
return this;
} public Builder nestedQueryId(String nestedQueryId) {
resultMapping.nestedQueryId = nestedQueryId;
return this;
} public Builder resultSet(String resultSet) {
resultMapping.resultSet = resultSet;
return this;
} public Builder foreignColumn(String foreignColumn) {
resultMapping.foreignColumn = foreignColumn;
return this;
} public Builder notNullColumns(Set<String> notNullColumns) {
resultMapping.notNullColumns = notNullColumns;
return this;
} public Builder columnPrefix(String columnPrefix) {
resultMapping.columnPrefix = columnPrefix;
return this;
} public Builder flags(List<ResultFlag> flags) {
resultMapping.flags = flags;
return this;
} public Builder typeHandler(TypeHandler<?> typeHandler) {
resultMapping.typeHandler = typeHandler;
return this;
} public Builder composites(List<ResultMapping> composites) {
resultMapping.composites = composites;
return this;
} public Builder lazy(boolean lazy) {
resultMapping.lazy = lazy;
return this;
} public ResultMapping build() {
// lock down collections
resultMapping.flags = Collections.unmodifiableList(resultMapping.flags);
resultMapping.composites = Collections.unmodifiableList(resultMapping.composites);
resolveTypeHandler();
validate();
return resultMapping;
} private void validate() {
// Issue #697: cannot define both nestedQueryId and nestedResultMapId
if (resultMapping.nestedQueryId != null && resultMapping.nestedResultMapId != null) {
throw new IllegalStateException("Cannot define both nestedQueryId and nestedResultMapId in property " + resultMapping.property);
}
// Issue #5: there should be no mappings without typehandler
if (resultMapping.nestedQueryId == null && resultMapping.nestedResultMapId == null && resultMapping.typeHandler == null) {
throw new IllegalStateException("No typehandler found for property " + resultMapping.property);
}
// Issue #4 and GH #39: column is optional only in nested resultmaps but not in the rest
if (resultMapping.nestedResultMapId == null && resultMapping.column == null && resultMapping.composites.isEmpty()) {
throw new IllegalStateException("Mapping is missing column attribute for property " + resultMapping.property);
}
if (resultMapping.getResultSet() != null) {
int numColumns = 0;
if (resultMapping.column != null) {
numColumns = resultMapping.column.split(",").length;
}
int numForeignColumns = 0;
if (resultMapping.foreignColumn != null) {
numForeignColumns = resultMapping.foreignColumn.split(",").length;
}
if (numColumns != numForeignColumns) {
throw new IllegalStateException("There should be the same number of columns and foreignColumns in property " + resultMapping.property);
}
}
} private void resolveTypeHandler() {
if (resultMapping.typeHandler == null && resultMapping.javaType != null) {
Configuration configuration = resultMapping.configuration;
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
resultMapping.typeHandler = typeHandlerRegistry.getTypeHandler(resultMapping.javaType, resultMapping.jdbcType);
}
} public Builder column(String column) {
resultMapping.column = column;
return this;
}
} public String getProperty() {
return property;
} public String getColumn() {
return column;
} public Class<?> getJavaType() {
return javaType;
} public JdbcType getJdbcType() {
return jdbcType;
} public TypeHandler<?> getTypeHandler() {
return typeHandler;
} public String getNestedResultMapId() {
return nestedResultMapId;
} public String getNestedQueryId() {
return nestedQueryId;
} public Set<String> getNotNullColumns() {
return notNullColumns;
} public String getColumnPrefix() {
return columnPrefix;
} public List<ResultFlag> getFlags() {
return flags;
} public List<ResultMapping> getComposites() {
return composites;
} public boolean isCompositeResult() {
return this.composites != null && !this.composites.isEmpty();
} public String getResultSet() {
return this.resultSet;
} public String getForeignColumn() {
return foreignColumn;
} public void setForeignColumn(String foreignColumn) {
this.foreignColumn = foreignColumn;
} public boolean isLazy() {
return lazy;
} public void setLazy(boolean lazy) {
this.lazy = lazy;
} @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
} ResultMapping that = (ResultMapping) o; return property != null && property.equals(that.property);
} @Override
public int hashCode() {
if (property != null) {
return property.hashCode();
} else if (column != null) {
return column.hashCode();
} else {
return 0;
}
}
}

ResultMap

package org.apache.ibatis.mapping;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set; import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.reflection.ParamNameUtil;
import org.apache.ibatis.session.Configuration; public class ResultMap {
private Configuration configuration; private String id;
private Class<?> type;
private List<ResultMapping> resultMappings;
private List<ResultMapping> idResultMappings;
private List<ResultMapping> constructorResultMappings;
private List<ResultMapping> propertyResultMappings;
private Set<String> mappedColumns;
private Set<String> mappedProperties;
private Discriminator discriminator;
private boolean hasNestedResultMaps;
private boolean hasNestedQueries;
private Boolean autoMapping; private ResultMap() {
} public static class Builder {
private static final Log log = LogFactory.getLog(Builder.class); private ResultMap resultMap = new ResultMap(); public Builder(Configuration configuration, String id, Class<?> type, List<ResultMapping> resultMappings) {
this(configuration, id, type, resultMappings, null);
} public Builder(Configuration configuration, String id, Class<?> type, List<ResultMapping> resultMappings, Boolean autoMapping) {
resultMap.configuration = configuration;
resultMap.id = id;
resultMap.type = type;
resultMap.resultMappings = resultMappings;
resultMap.autoMapping = autoMapping;
} public Builder discriminator(Discriminator discriminator) {
resultMap.discriminator = discriminator;
return this;
} public Class<?> type() {
return resultMap.type;
} public ResultMap build() {
if (resultMap.id == null) {
throw new IllegalArgumentException("ResultMaps must have an id");
}
resultMap.mappedColumns = new HashSet<>();
resultMap.mappedProperties = new HashSet<>();
resultMap.idResultMappings = new ArrayList<>();
resultMap.constructorResultMappings = new ArrayList<>();
resultMap.propertyResultMappings = new ArrayList<>();
final List<String> constructorArgNames = new ArrayList<>();
for (ResultMapping resultMapping : resultMap.resultMappings) {
resultMap.hasNestedQueries = resultMap.hasNestedQueries || resultMapping.getNestedQueryId() != null;
resultMap.hasNestedResultMaps = resultMap.hasNestedResultMaps || (resultMapping.getNestedResultMapId() != null && resultMapping.getResultSet() == null);
final String column = resultMapping.getColumn();
if (column != null) {
resultMap.mappedColumns.add(column.toUpperCase(Locale.ENGLISH));
} else if (resultMapping.isCompositeResult()) {
for (ResultMapping compositeResultMapping : resultMapping.getComposites()) {
final String compositeColumn = compositeResultMapping.getColumn();
if (compositeColumn != null) {
resultMap.mappedColumns.add(compositeColumn.toUpperCase(Locale.ENGLISH));
}
}
}
final String property = resultMapping.getProperty();
if (property != null) {
resultMap.mappedProperties.add(property);
}
if (resultMapping.getFlags().contains(ResultFlag.CONSTRUCTOR)) {
resultMap.constructorResultMappings.add(resultMapping);
if (resultMapping.getProperty() != null) {
constructorArgNames.add(resultMapping.getProperty());
}
} else {
resultMap.propertyResultMappings.add(resultMapping);
}
if (resultMapping.getFlags().contains(ResultFlag.ID)) {
resultMap.idResultMappings.add(resultMapping);
}
}
if (resultMap.idResultMappings.isEmpty()) {
resultMap.idResultMappings.addAll(resultMap.resultMappings);
}
if (!constructorArgNames.isEmpty()) {
final List<String> actualArgNames = argNamesOfMatchingConstructor(constructorArgNames);
if (actualArgNames == null) {
throw new BuilderException("Error in result map '" + resultMap.id
+ "'. Failed to find a constructor in '"
+ resultMap.getType().getName() + "' by arg names " + constructorArgNames
+ ". There might be more info in debug log.");
}
resultMap.constructorResultMappings.sort((o1, o2) -> {
int paramIdx1 = actualArgNames.indexOf(o1.getProperty());
int paramIdx2 = actualArgNames.indexOf(o2.getProperty());
return paramIdx1 - paramIdx2;
});
}
// lock down collections
resultMap.resultMappings = Collections.unmodifiableList(resultMap.resultMappings);
resultMap.idResultMappings = Collections.unmodifiableList(resultMap.idResultMappings);
resultMap.constructorResultMappings = Collections.unmodifiableList(resultMap.constructorResultMappings);
resultMap.propertyResultMappings = Collections.unmodifiableList(resultMap.propertyResultMappings);
resultMap.mappedColumns = Collections.unmodifiableSet(resultMap.mappedColumns);
return resultMap;
} private List<String> argNamesOfMatchingConstructor(List<String> constructorArgNames) {
Constructor<?>[] constructors = resultMap.type.getDeclaredConstructors();
for (Constructor<?> constructor : constructors) {
Class<?>[] paramTypes = constructor.getParameterTypes();
if (constructorArgNames.size() == paramTypes.length) {
List<String> paramNames = getArgNames(constructor);
if (constructorArgNames.containsAll(paramNames)
&& argTypesMatch(constructorArgNames, paramTypes, paramNames)) {
return paramNames;
}
}
}
return null;
} private boolean argTypesMatch(final List<String> constructorArgNames,
Class<?>[] paramTypes, List<String> paramNames) {
for (int i = 0; i < constructorArgNames.size(); i++) {
Class<?> actualType = paramTypes[paramNames.indexOf(constructorArgNames.get(i))];
Class<?> specifiedType = resultMap.constructorResultMappings.get(i).getJavaType();
if (!actualType.equals(specifiedType)) {
if (log.isDebugEnabled()) {
log.debug("While building result map '" + resultMap.id
+ "', found a constructor with arg names " + constructorArgNames
+ ", but the type of '" + constructorArgNames.get(i)
+ "' did not match. Specified: [" + specifiedType.getName() + "] Declared: ["
+ actualType.getName() + "]");
}
return false;
}
}
return true;
} private List<String> getArgNames(Constructor<?> constructor) {
List<String> paramNames = new ArrayList<>();
List<String> actualParamNames = null;
final Annotation[][] paramAnnotations = constructor.getParameterAnnotations();
int paramCount = paramAnnotations.length;
for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
String name = null;
for (Annotation annotation : paramAnnotations[paramIndex]) {
if (annotation instanceof Param) {
name = ((Param) annotation).value();
break;
}
}
if (name == null && resultMap.configuration.isUseActualParamName()) {
if (actualParamNames == null) {
actualParamNames = ParamNameUtil.getParamNames(constructor);
}
if (actualParamNames.size() > paramIndex) {
name = actualParamNames.get(paramIndex);
}
}
paramNames.add(name != null ? name : "arg" + paramIndex);
}
return paramNames;
}
} public String getId() {
return id;
} public boolean hasNestedResultMaps() {
return hasNestedResultMaps;
} public boolean hasNestedQueries() {
return hasNestedQueries;
} public Class<?> getType() {
return type;
} public List<ResultMapping> getResultMappings() {
return resultMappings;
} public List<ResultMapping> getConstructorResultMappings() {
return constructorResultMappings;
} public List<ResultMapping> getPropertyResultMappings() {
return propertyResultMappings;
} public List<ResultMapping> getIdResultMappings() {
return idResultMappings;
} public Set<String> getMappedColumns() {
return mappedColumns;
} public Set<String> getMappedProperties() {
return mappedProperties;
} public Discriminator getDiscriminator() {
return discriminator;
} public void forceNestedResultMaps() {
hasNestedResultMaps = true;
} public Boolean getAutoMapping() {
return autoMapping;
} }

MyBatis的ResultMapping和ResultMap的更多相关文章

  1. MyBatis映射文件的resultMap如何做表关联

    MyBatis的核心是其映射文件,SqlMap文件,里面配置了项目中用到了什么SQL语句,和数据库相关的逻辑都在这个映射文件里.顾名思义,映射文件就是对Java对象和SQL的映射.这里简单介绍一下映射 ...

  2. MyBatis中resultType和resultMap的区别

    resultType和resultMap功能类似  ,都是返回对象信息  ,但是resultMap要更强大一些 ,可自定义.因为resultMap要配置一下,表和类的一一对应关系,所以说就算你的字段名 ...

  3. MyBatis有关resultType和resultMap差异

    MyBatis有关resultType和resultMap差异   MyBatis中在查询进行select映射的时候,返回类型能够用resultType,也能够用resultMap.resultTyp ...

  4. mybatis源码-原来resultMap解析完是这样

    目录 1 两个基础类 1.1 列映射类ResultMapping 1.2 结果集映射类ResultMap 2. 解析 2.1 入口函数 2.2 解析流程 2.3 获取 id 2.4 解析结果集的类型 ...

  5. Mybatis 高级结果映射 ResultMap Association Collection

    在阅读本文章时,先说几个mybatis中容易混淆的地方: 1. mybatis中的列不是数据库里的列而是查询里的列,可以是别名(如 select user_name as userName,这时col ...

  6. MyBatis魔法堂:ResultMap详解

    一.前言   MyBatis是基于“数据库结构不可控”的思想建立的,也就是我们希望数据库遵循第三范式或BCNF,但实际事与愿违,那么结果集映射就是MyBatis为我们提供这种理想与现实间转换的手段了, ...

  7. 错误Mybatis 元素类型为 "resultMap" 的内容必须匹配 "(constructor?,id*,result*,association*,collection*,discriminat

    今天算是见识了什么事顺序的重要性. 在使用mybatis时由于联合了其他的表,用到了resultMap,之后外加association这一项.可是在替换对应字段的位置上加上association总是报 ...

  8. MyBatis学习笔记之resultMap

    使用mybatis不能不说的是resultMap 相比resultClass来说resultMap可以适应更复杂的关系映射,允许指定字段的数据类型,支持“select *” ,并不要求定义 Resul ...

  9. 解决 Mybatis 元素类型为 "resultMap" 的内容必须匹配 "(constructor?,id*,result*,association*,collection*,discriminat

    在配置 mybatis mapper.xml文件时, 一不小心就会报如下类似的异常: Caused by: org.springframework.beans.factory.BeanCreation ...

随机推荐

  1. Python3 类的继承小练习

    1.打印并解释结果 class Parent(object): x = 1 class Child1(Parent): pass class Child2(Parent): pass print(Pa ...

  2. jvm调优、常用工具

    ps -ef | grep java查出进程id jmap -heap ID 查出jvm配置信息 加入参数:打印Gc日志,分析 GC日志分析工具: GCeasy 降低minor gc 和 full g ...

  3. 【Maven】plugin使用学习

    Maven plugin使用学习 官网可用的插件:http://maven.apache.org/plugins/index.html 目录 ============================= ...

  4. Web基础了解版03-jQuery

    jQuery jQuery,顾名思义,也就是JavaScript和查询(Query)极大地简化了JavaScript开发人员遍历HTML文档.操作DOM.处理事件.执行动画和开发Ajax. jQuer ...

  5. Winform修改配置文件节点保存到配置文件

    主要使用: Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ...

  6. LVM(逻辑卷管理器)部署、扩容、缩小

    物理卷 -- Physical Volume -- PV 卷组  -- Volume Group  -- VG 逻辑卷 -- Logical Volume -- LV 1.硬盘设备管理技术虽然能够有效 ...

  7. NPOI 工作簿一般设置

    HSSFWorkbook workbook = new HSSFWorkbook(); //声明一个空白的工作簿,也可以将已有文件转化为文件流作为参数声明一个工作簿,这样这个工作簿里就会有已有文件中的 ...

  8. vue & nodejs jwt 的基于token身份验证

    现在比较流行的验证方式,是带着token的登录验证 原理 1. 登陆时,客户端发送用户名密码 2. 服务端验证用户名密码是否正确,校验通过就会生成一个有时效的token串,发送给客户端 3. 客户端储 ...

  9. 使用VMware安装CentOS 7

    环境:Windows10 , VMware Workstation 15 Player, CentOS 7 为什么选择CentOS ? 主流: 目前的Linux操作系统主要应用于生产环境,主流企业级L ...

  10. 【30天自制操作系统】day04:C语言与目前执行流程图

    用 C 语言直接写入内存 原来依靠汇编 void io_hlt(void); void write_mem8(int addr, int data); void HariMain(void){ int ...