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. Python之工作方向

    "python基础-->(函数/面向对象/网络编程(scoket套接字)/并发编程(mutiprocessing)) "运维+web开发-->页面展示(django/f ...

  2. MySql数据库之常用数据类型及常用约束简述

    本文呢,主要给大家简述一下数据库中常用的几种数据类型以及约束. 1.数据类型 数据类型,是指数据表中可以存储的数据的种类. 数据库中常用的数据类型有: 1.整型:int.bit 2.小数:decima ...

  3. Nginx入门教程-简介、安装、反向代理、负载均衡、动静分离使用实例

    场景 Nginx入门简介和反向代理.负载均衡.动静分离理解 https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/102790862 Ub ...

  4. 渗透测试初学者的靶场实战 3--墨者学院SQL注入—宽字节盲注

    墨者SQL注入-MYSQL数据库实战环境 实践步骤 1. 决断注入点 输入单引号,提示错误信息: 输入and 1=1 返回页面正常: 输入 and 1=2 返回正常 输入-1,返回异常: 2. 带入s ...

  5. Hack the De-ICE: S1.120 VM (Boot to Root)

    下载地址: https://www.vulnhub.com/entry/de-ice-s1120,10/ 静态IP:192.168.1.120 主机扫描: ╰─ nmap -p1-65535 -sV ...

  6. Android 自定义吐司通知

    protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentV ...

  7. 【Linux 命令】cp 命令详解

    Linux 命令之 cp 命令详解 一.cp 命令简介 cp 命令主要用于复制文件或目录.即用来将一个或多个源文件或者目录复制到指定的目的文件或目录. cp 命令可以将单个源文件复制成一个指定文件名的 ...

  8. 【转载】Docker registry仓库历史镜像批量清理

    前言 在jenkins CI/CD流水线中以自动打包并push镜像的方式运行了一段时间之后, docker registry中堆积的历史镜像数量极多,磁盘空间告急,为此,有必要定期做镜像的清理,并释放 ...

  9. 【10分钟学Spring】:(二)一文搞懂spring依赖注入(DI)

    Spring最基础的特性就是创建bean.管理bean之间的依赖关系.下面通过具体实例演示该如何装配我们应用中的bean. Spring提供了三种主要的装配机制 在xml中进行显示的配置 在Java中 ...

  10. 【THUPC 2018】赛艇

    Problem Description Lavender.Caryophyllus.Jasmine.Dianthus现在在玩一款名叫"赛艇"的游戏. 这个游戏的规则是这样的: 玩家 ...