移除selectIgnore,新增FULL JOIN,优化对TypeHandle的支持

This commit is contained in:
yulichang 2022-11-01 19:04:37 +08:00
parent 0a36a578f0
commit d260884a3c
19 changed files with 347 additions and 579 deletions

View File

@ -4,7 +4,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join</artifactId>
<version>1.2.4</version>
<version>1.2.5</version>
<name>mybatis-plus-join</name>
<description>An enhanced toolkit of Mybatis-Plus to simplify development.</description>
<url>https://github.com/yulichang/mybatis-plus-join</url>

View File

@ -1,31 +1,19 @@
package com.baomidou.mybatisplus.core.metadata;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.core.toolkit.ClassUtils;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.github.yulichang.annotation.EntityMapping;
import com.github.yulichang.annotation.FieldMapping;
import com.github.yulichang.exception.MPJException;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.ResultFlag;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.reflection.Reflector;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.session.Configuration;
import com.github.yulichang.mapper.MPJTableInfo;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static java.util.stream.Collectors.toList;
/**
* 拷贝 {@link TableInfoHelper}
*
@ -41,21 +29,11 @@ import static java.util.stream.Collectors.toList;
@SuppressWarnings("deprecation")
public class MPJTableInfoHelper {
private static final Log logger = LogFactory.getLog(TableInfoHelper.class);
/**
* 储存反射类表信息
*/
private static final Map<Class<?>, MPJTableInfo> TABLE_INFO_CACHE = new ConcurrentHashMap<>();
/**
* 默认表主键名称
*/
private static final String DEFAULT_ID_NAME = "id";
/**
* <p>
* 获取实体映射表信息
@ -71,30 +49,6 @@ public class MPJTableInfoHelper {
return TABLE_INFO_CACHE.get(clazz);
}
/**
* <p>
* 实体类反射获取表信息初始化
* </p>
*
* @param clazz 反射实体类
* @param mapperClass mapperClass
*/
@SuppressWarnings("unused")
public synchronized static void initTableInfo(MapperBuilderAssistant builderAssistant, Class<?> clazz, Class<?> mapperClass) {
MPJTableInfo targetTableInfo = TABLE_INFO_CACHE.get(clazz);
final Configuration configuration = builderAssistant.getConfiguration();
if (targetTableInfo != null) {
Configuration oldConfiguration = targetTableInfo.getTableInfo().getConfiguration();
if (!oldConfiguration.equals(configuration)) {
// 不是同一个 Configuration,进行重新初始化
initTableInfo(configuration, builderAssistant.getCurrentNamespace(), clazz, mapperClass);
}
return;
}
initTableInfo(configuration, builderAssistant.getCurrentNamespace(), clazz, mapperClass);
}
/**
* <p>
* 获取所有实体映射表信息
@ -106,59 +60,6 @@ public class MPJTableInfoHelper {
return Collections.unmodifiableList(new ArrayList<>(TABLE_INFO_CACHE.values()));
}
/**
* <p>
* 实体类反射获取表信息初始化
* </p>
*
* @param clazz 反射实体类
* @return 数据库表反射信息
*/
public synchronized static MPJTableInfo initTableInfo(Configuration configuration, String currentNamespace, Class<?> clazz, Class<?> mapperClass) {
MPJTableInfo info = TABLE_INFO_CACHE.get(clazz);
if (info != null) {
return info;
}
/* 没有获取到缓存信息,则初始化 */
MPJTableInfo mpjTableInfo = new MPJTableInfo();
mpjTableInfo.setMapperClass(mapperClass);
TableInfo tableInfo = TableInfoHelper.getTableInfo(clazz);
if (tableInfo != null) {
mpjTableInfo.setTableInfo(tableInfo);
initMapping(mpjTableInfo);
/* 添加缓存 */
TABLE_INFO_CACHE.put(clazz, mpjTableInfo);
return mpjTableInfo;
}
tableInfo = new TableInfo(clazz);
mpjTableInfo.setTableInfo(tableInfo);
tableInfo.setCurrentNamespace(currentNamespace);
tableInfo.setConfiguration(configuration);
GlobalConfig globalConfig = GlobalConfigUtils.getGlobalConfig(configuration);
/* 初始化表名相关 */
final String[] excludeProperty = initTableName(clazz, globalConfig, tableInfo);
List<String> excludePropertyList = excludeProperty != null && excludeProperty.length > 0 ? Arrays.asList(excludeProperty) : Collections.emptyList();
/* 初始化字段相关 */
initTableFields(clazz, globalConfig, mpjTableInfo, excludePropertyList);
/* 自动构建 resultMap */
initResultMapIfNeed(tableInfo);
/* 添加缓存 */
TABLE_INFO_CACHE.put(clazz, mpjTableInfo);
/* 缓存 lambda */
LambdaUtils.installCache(tableInfo);
/* 初始化映射关系 */
initMapping(mpjTableInfo);
return mpjTableInfo;
}
/**
* <p>
* 实体类反射获取表信息初始化
@ -182,204 +83,6 @@ public class MPJTableInfoHelper {
TABLE_INFO_CACHE.put(clazz, mpjTableInfo);
}
/**
* 自动构建 resultMap 并注入(如果条件符合的话)
*/
private static void initResultMapIfNeed(TableInfo tableInfo) {
if (tableInfo.isAutoInitResultMap() && null == tableInfo.getResultMap()) {
String id = tableInfo.getCurrentNamespace() + ".mybatis-plus-join_" + tableInfo.getEntityType().getSimpleName();
tableInfo.setResultMap(id);
if (tableInfo.getConfiguration().getResultMapNames().contains(id)) {
tableInfo.getConfiguration().getResultMap(id);
}
List<ResultMapping> resultMappings = new ArrayList<>();
if (tableInfo.havePK()) {
ResultMapping idMapping = new ResultMapping.Builder(tableInfo.getConfiguration(), tableInfo.getKeyProperty(),
tableInfo.getKeyColumn(), tableInfo.getKeyType())
.flags(Collections.singletonList(ResultFlag.ID)).build();
resultMappings.add(idMapping);
}
if (CollectionUtils.isNotEmpty(tableInfo.getFieldList())) {
tableInfo.getFieldList().forEach(i -> resultMappings.add(i.getResultMapping(tableInfo.getConfiguration())));
}
ResultMap resultMap = new ResultMap.Builder(tableInfo.getConfiguration(), id, tableInfo.getEntityType(),
resultMappings).build();
tableInfo.getConfiguration().addResultMap(resultMap);
}
}
/**
* <p>
* 初始化 表数据库类型,表名,resultMap
* </p>
*
* @param clazz 实体类
* @param globalConfig 全局配置
* @param tableInfo 数据库表反射信息
* @return 需要排除的字段名
*/
private static String[] initTableName(Class<?> clazz, GlobalConfig globalConfig, TableInfo tableInfo) {
/* 数据库全局配置 */
GlobalConfig.DbConfig dbConfig = globalConfig.getDbConfig();
TableName table = clazz.getAnnotation(TableName.class);
String tableName = clazz.getSimpleName();
String tablePrefix = dbConfig.getTablePrefix();
String schema = dbConfig.getSchema();
boolean tablePrefixEffect = true;
String[] excludeProperty = null;
if (table != null) {
if (StringUtils.isNotBlank(table.value())) {
tableName = table.value();
if (StringUtils.isNotBlank(tablePrefix) && !table.keepGlobalPrefix()) {
tablePrefixEffect = false;
}
} else {
tableName = initTableNameWithDbConfig(tableName, dbConfig);
}
if (StringUtils.isNotBlank(table.schema())) {
schema = table.schema();
}
/* 表结果集映射 */
if (StringUtils.isNotBlank(table.resultMap())) {
tableInfo.setResultMap(table.resultMap());
}
tableInfo.setAutoInitResultMap(table.autoResultMap());
excludeProperty = table.excludeProperty();
} else {
tableName = initTableNameWithDbConfig(tableName, dbConfig);
}
String targetTableName = tableName;
if (StringUtils.isNotBlank(tablePrefix) && tablePrefixEffect) {
targetTableName = tablePrefix + targetTableName;
}
if (StringUtils.isNotBlank(schema)) {
targetTableName = schema + StringPool.DOT + targetTableName;
}
tableInfo.setTableName(targetTableName);
return excludeProperty;
}
/**
* 根据 DbConfig 初始化 表名
*
* @param className 类名
* @param dbConfig DbConfig
* @return 表名
*/
private static String initTableNameWithDbConfig(String className, GlobalConfig.DbConfig dbConfig) {
String tableName = className;
// 开启表名下划线申明
if (dbConfig.isTableUnderline()) {
tableName = StringUtils.camelToUnderline(tableName);
}
// 大写命名判断
if (dbConfig.isCapitalMode()) {
tableName = tableName.toUpperCase();
} else {
// 首字母小写
tableName = StringUtils.firstToLowerCase(tableName);
}
return tableName;
}
/**
* <p>
* 初始化 表主键,表字段
* </p>
*
* @param clazz 实体类
* @param globalConfig 全局配置
* @param mpjTableInfo 数据库表反射信息
*/
private static void initTableFields(Class<?> clazz, GlobalConfig globalConfig, MPJTableInfo mpjTableInfo, List<String> excludeProperty) {
/* 数据库全局配置 */
GlobalConfig.DbConfig dbConfig = globalConfig.getDbConfig();
ReflectorFactory reflectorFactory = mpjTableInfo.getTableInfo().getConfiguration().getReflectorFactory();
Reflector reflector = reflectorFactory.findForClass(clazz);
List<Field> list = getAllFields(clazz);
// 标记是否读取到主键
boolean isReadPK = false;
// 是否存在 @TableId 注解
boolean existTableId = isExistTableId(list);
// 是否存在 @TableLogic 注解
boolean existTableLogic = isExistTableLogic(list);
List<TableFieldInfo> fieldList = new ArrayList<>(list.size());
for (Field field : list) {
if (excludeProperty.contains(field.getName())) {
continue;
}
/* 主键ID 初始化 */
if (existTableId) {
TableId tableId = field.getAnnotation(TableId.class);
if (tableId != null) {
if (isReadPK) {
throw ExceptionUtils.mpe("@TableId can't more than one in Class: \"%s\".", clazz.getName());
} else {
initTableIdWithAnnotation(dbConfig, mpjTableInfo.getTableInfo(), field, tableId, reflector);
isReadPK = true;
continue;
}
}
} else if (!isReadPK) {
isReadPK = initTableIdWithoutAnnotation(dbConfig, mpjTableInfo.getTableInfo(), field, reflector);
if (isReadPK) {
continue;
}
}
final TableField tableField = field.getAnnotation(TableField.class);
/* 有 @TableField 注解的字段初始化 */
if (tableField != null) {
fieldList.add(new TableFieldInfo(dbConfig, mpjTableInfo.getTableInfo(), field, tableField, reflector, existTableLogic));
continue;
}
/* 无 @TableField 注解的字段初始化 */
fieldList.add(new TableFieldInfo(dbConfig, mpjTableInfo.getTableInfo(), field, reflector, existTableLogic));
}
/* 字段列表 */
mpjTableInfo.getTableInfo().setFieldList(fieldList);
/* 未发现主键注解,提示警告信息 */
if (!isReadPK) {
logger.warn(String.format("Can not find table primary key in Class: \"%s\".", clazz.getName()));
}
}
/**
* <p>
* 判断主键注解是否存在
* </p>
*
* @param list 字段列表
* @return true 为存在 @TableId 注解;
*/
public static boolean isExistTableId(List<Field> list) {
return list.stream().anyMatch(field -> field.isAnnotationPresent(TableId.class));
}
/**
* <p>
* 判断逻辑删除注解是否存在
* </p>
*
* @param list 字段列表
* @return true 为存在 @TableId 注解;
*/
public static boolean isExistTableLogic(List<Field> list) {
return list.stream().anyMatch(field -> field.isAnnotationPresent(TableLogic.class));
}
private static boolean isExistMapping(Class<?> clazz) {
return ReflectionKit.getFieldList(ClassUtils.getUserClass(clazz)).stream().anyMatch(field -> field.isAnnotationPresent(EntityMapping.class));
}
@ -388,137 +91,6 @@ public class MPJTableInfoHelper {
return ReflectionKit.getFieldList(ClassUtils.getUserClass(clazz)).stream().anyMatch(field -> field.isAnnotationPresent(FieldMapping.class));
}
/**
* <p>
* 主键属性初始化
* </p>
*
* @param dbConfig 全局配置信息
* @param tableInfo 表信息
* @param field 字段
* @param tableId 注解
* @param reflector Reflector
*/
private static void initTableIdWithAnnotation(GlobalConfig.DbConfig dbConfig, TableInfo tableInfo,
Field field, TableId tableId, Reflector reflector) {
boolean underCamel = tableInfo.isUnderCamel();
final String property = field.getName();
if (field.getAnnotation(TableField.class) != null) {
logger.warn(String.format("This \"%s\" is the table primary key by @TableId annotation in Class: \"%s\",So @TableField annotation will not work!",
property, tableInfo.getEntityType().getName()));
}
/* 主键策略( 注解 > 全局 */
// 设置 Sequence 其他策略无效
if (IdType.NONE == tableId.type()) {
tableInfo.setIdType(dbConfig.getIdType());
} else {
tableInfo.setIdType(tableId.type());
}
/* 字段 */
String column = property;
if (StringUtils.isNotBlank(tableId.value())) {
column = tableId.value();
} else {
// 开启字段下划线申明
if (underCamel) {
column = StringUtils.camelToUnderline(column);
}
// 全局大写命名
if (dbConfig.isCapitalMode()) {
column = column.toUpperCase();
}
}
final Class<?> keyType = reflector.getGetterType(property);
if (keyType.isPrimitive()) {
logger.warn(String.format("This primary key of \"%s\" is primitive !不建议如此请使用包装类 in Class: \"%s\"",
property, tableInfo.getEntityType().getName()));
}
tableInfo.setKeyRelated(checkRelated(underCamel, property, column))
.setKeyColumn(column)
.setKeyProperty(property)
.setKeyType(keyType);
}
/**
* <p>
* 主键属性初始化
* </p>
*
* @param tableInfo 表信息
* @param field 字段
* @param reflector Reflector
* @return true 继续下一个属性判断返回 continue;
*/
private static boolean initTableIdWithoutAnnotation(GlobalConfig.DbConfig dbConfig, TableInfo tableInfo,
Field field, Reflector reflector) {
final String property = field.getName();
if (DEFAULT_ID_NAME.equalsIgnoreCase(property)) {
if (field.getAnnotation(TableField.class) != null) {
logger.warn(String.format("This \"%s\" is the table primary key by default name for `id` in Class: \"%s\",So @TableField will not work!",
property, tableInfo.getEntityType().getName()));
}
String column = property;
if (dbConfig.isCapitalMode()) {
column = column.toUpperCase();
}
final Class<?> keyType = reflector.getGetterType(property);
if (keyType.isPrimitive()) {
logger.warn(String.format("This primary key of \"%s\" is primitive !不建议如此请使用包装类 in Class: \"%s\"",
property, tableInfo.getEntityType().getName()));
}
tableInfo.setKeyRelated(checkRelated(tableInfo.isUnderCamel(), property, column))
.setIdType(dbConfig.getIdType())
.setKeyColumn(column)
.setKeyProperty(property)
.setKeyType(keyType);
return true;
}
return false;
}
/**
* 判定 related 的值
* <p>
* true 表示不符合规则
*
* @param underCamel 驼峰命名
* @param property 属性名
* @param column 字段名
* @return related
*/
public static boolean checkRelated(boolean underCamel, String property, String column) {
column = StringUtils.getTargetColumn(column);
String propertyUpper = property.toUpperCase(Locale.ENGLISH);
String columnUpper = column.toUpperCase(Locale.ENGLISH);
if (underCamel) {
// 开启了驼峰并且 column 包含下划线
return !(propertyUpper.equals(columnUpper) ||
propertyUpper.equals(columnUpper.replace(StringPool.UNDERSCORE, StringPool.EMPTY)));
} else {
// 未开启驼峰,直接判断 property 是否与 column 相同(全大写)
return !propertyUpper.equals(columnUpper);
}
}
/**
* <p>
* 获取该类的所有属性列表
* </p>
*
* @param clazz 反射类
* @return 属性集合
*/
public static List<Field> getAllFields(Class<?> clazz) {
List<Field> fieldList = ReflectionKit.getFieldList(ClassUtils.getUserClass(clazz));
return fieldList.stream()
.filter(field -> {
/* 过滤注解非表字段属性 */
TableField tableField = field.getAnnotation(TableField.class);
return (tableField == null || tableField.exist());
}).collect(toList());
}
/**
* 初始化映射相关
*/
@ -531,19 +103,19 @@ public class MPJTableInfoHelper {
mpjTableInfo.setHasMappingField(existMappingField);
mpjTableInfo.setHasMappingOrField(existMapping || existMappingField);
/* 关系映射初始化 */
List<MPJTableFieldInfo> mpjFieldList = new ArrayList<>();
List<com.github.yulichang.mapper.MPJTableFieldInfo> mpjFieldList = new ArrayList<>();
List<Field> fields = ReflectionKit.getFieldList(ClassUtils.getUserClass(mpjTableInfo.getTableInfo().getEntityType()));
for (Field field : fields) {
if (existMapping) {
EntityMapping mapping = field.getAnnotation(EntityMapping.class);
if (mapping != null) {
mpjFieldList.add(new MPJTableFieldInfo(mpjTableInfo.getTableInfo().getEntityType(), mapping, field));
mpjFieldList.add(new com.github.yulichang.mapper.MPJTableFieldInfo(mpjTableInfo.getTableInfo().getEntityType(), mapping, field));
}
}
if (existMappingField) {
FieldMapping mapping = field.getAnnotation(FieldMapping.class);
if (mapping != null) {
mpjFieldList.add(new MPJTableFieldInfo(mpjTableInfo.getTableInfo().getEntityType(), mapping, field));
mpjFieldList.add(new com.github.yulichang.mapper.MPJTableFieldInfo(mpjTableInfo.getTableInfo().getEntityType(), mapping, field));
}
}
}

View File

@ -7,6 +7,8 @@ import com.baomidou.mybatisplus.core.metadata.*;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.github.yulichang.base.mapper.wrapper.MappingQuery;
import com.github.yulichang.mapper.MPJTableFieldInfo;
import com.github.yulichang.mapper.MPJTableInfo;
import com.github.yulichang.toolkit.LambdaUtils;
import java.io.Serializable;

View File

@ -3,8 +3,8 @@ package com.github.yulichang.base.mapper.wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlKeyword;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.MPJMappingWrapper;
import com.baomidou.mybatisplus.core.metadata.MPJTableFieldInfo;
import com.github.yulichang.mapper.MPJMappingWrapper;
import com.github.yulichang.mapper.MPJTableFieldInfo;
import java.util.List;

View File

@ -1,7 +1,7 @@
package com.github.yulichang.config;
import com.baomidou.mybatisplus.core.metadata.MPJTableInfoHelper;
import com.baomidou.mybatisplus.core.metadata.MPJTableMapperHelper;
import com.github.yulichang.mapper.MPJTableMapperHelper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;

View File

@ -15,7 +15,7 @@ import com.baomidou.mybatisplus.core.injector.methods.UpdateById;
import com.baomidou.mybatisplus.core.injector.methods.SelectBatchByIds;
import com.baomidou.mybatisplus.core.injector.methods.SelectByMap;
import com.baomidou.mybatisplus.core.mapper.Mapper;
import com.baomidou.mybatisplus.core.metadata.MPJTableMapperHelper;
import com.github.yulichang.mapper.MPJTableMapperHelper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.ClassUtils;
import com.github.yulichang.method.*;

View File

@ -1,15 +1,19 @@
package com.github.yulichang.interceptor;
import com.baomidou.mybatisplus.core.metadata.MPJTableInfo;
import com.baomidou.mybatisplus.core.metadata.MPJTableInfoHelper;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.yulichang.interfaces.MPJBaseJoin;
import com.github.yulichang.method.MPJResultType;
import com.github.yulichang.toolkit.Constant;
import com.github.yulichang.toolkit.ReflectionKit;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.github.yulichang.wrapper.SelectColumn;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
@ -23,13 +27,17 @@ import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.core.annotation.Order;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.apache.ibatis.type.UnknownTypeHandler;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* 连表拦截器
@ -43,11 +51,10 @@ import java.util.concurrent.ConcurrentHashMap;
public class MPJInterceptor implements Interceptor {
private static final Log logger = LogFactory.getLog(MPJInterceptor.class);
private static final List<ResultMapping> EMPTY_RESULT_MAPPING = new ArrayList<>(0);
/**
* 缓存MappedStatement,不需要每次都去重构建MappedStatement
* 缓存MappedStatement,不需要每次都去重构建MappedStatement
*/
private static final Map<String, Map<Configuration, MappedStatement>> MS_CACHE = new ConcurrentHashMap<>();
@ -72,7 +79,7 @@ public class MPJInterceptor implements Interceptor {
if (CollectionUtils.isNotEmpty(list)) {
ResultMap resultMap = list.get(0);
if (resultMap.getType() == MPJResultType.class) {
args[0] = newMappedStatement(ms, clazz);
args[0] = getMappedStatement(ms, clazz, ew);
}
}
}
@ -84,10 +91,16 @@ public class MPJInterceptor implements Interceptor {
/**
* 构建新的MappedStatement
* 获取MappedStatement
*/
public MappedStatement newMappedStatement(MappedStatement ms, Class<?> resultType) {
public MappedStatement getMappedStatement(MappedStatement ms, Class<?> resultType, Object ew) {
String id = ms.getId() + StringPool.UNDERSCORE + resultType.getName();
if (ew instanceof MPJLambdaWrapper) {
//不走缓存
return buildMappedStatement(ms, resultType, ew, id);
}
//走缓存
Map<Configuration, MappedStatement> statementMap = MS_CACHE.get(id);
if (CollectionUtils.isNotEmpty(statementMap)) {
MappedStatement statement = statementMap.get(ms.getConfiguration());
@ -95,6 +108,20 @@ public class MPJInterceptor implements Interceptor {
return statement;
}
}
MappedStatement mappedStatement = buildMappedStatement(ms, resultType, ew, id);
if (statementMap == null) {
statementMap = new ConcurrentHashMap<>();
MS_CACHE.put(id, statementMap);
}
statementMap.put(ms.getConfiguration(), mappedStatement);
return mappedStatement;
}
/**
* 构建新的MappedStatement
*/
private MappedStatement buildMappedStatement(MappedStatement ms, Class<?> resultType, Object ew, String id) {
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), id, ms.getSqlSource(), ms.getSqlCommandType())
.resource(ms.getResource())
.fetchSize(ms.getFetchSize())
@ -110,33 +137,90 @@ public class MPJInterceptor implements Interceptor {
builder.keyProperty(String.join(StringPool.COMMA, ms.getKeyProperties()));
}
List<ResultMap> resultMaps = new ArrayList<>();
resultMaps.add(newResultMap(ms, resultType));
resultMaps.add(buildResultMap(ms, resultType, ew));
builder.resultMaps(resultMaps);
MappedStatement mappedStatement = builder.build();
if (statementMap == null) {
statementMap = new ConcurrentHashMap<>();
MS_CACHE.put(id, statementMap);
}
statementMap.put(ms.getConfiguration(), mappedStatement);
return mappedStatement;
return builder.build();
}
/**
* 构建resultMap
*/
private ResultMap newResultMap(MappedStatement ms, Class<?> resultType) {
@SuppressWarnings({"rawtypes", "unchecked", "ConstantConditions"})
private ResultMap buildResultMap(MappedStatement ms, Class<?> resultType, Object obj) {
TableInfo tableInfo = TableInfoHelper.getTableInfo(resultType);
if (tableInfo != null && tableInfo.isAutoInitResultMap() && tableInfo.getEntityType() == resultType) {
return ms.getConfiguration().getResultMap(tableInfo.getResultMap());
if (tableInfo == null || !(obj instanceof MPJLambdaWrapper)) {
return getDefaultResultMap(tableInfo, ms, resultType);
}
MPJTableInfo infoDTO = MPJTableInfoHelper.getTableInfo(resultType);
if (infoDTO == null) {
infoDTO = MPJTableInfoHelper.initTableInfo(ms.getConfiguration(),
ms.getId().substring(0, ms.getId().lastIndexOf(".")), resultType, null);
MPJLambdaWrapper wrapper = (MPJLambdaWrapper) obj;
String currentNamespace = ms.getResource().split(StringPool.SPACE)[0];
String id = currentNamespace + StringPool.DOT + Constants.MYBATIS_PLUS + StringPool.UNDERSCORE + resultType.getSimpleName();
if (wrapper.isResultMap()) {
//TODO
//添加 collection 标签
return new ResultMap.Builder(ms.getConfiguration(), ms.getId(), resultType, EMPTY_RESULT_MAPPING).build();
} else {
List<SelectColumn> columnList = wrapper.getSelectColumns();
List<ResultMapping> resultMappings = new ArrayList<>();
columnList.forEach(i -> {
//别名优先
if (StringUtils.isNotBlank(i.getAlias())) {
resultMappings.add(new ResultMapping.Builder(ms.getConfiguration(), i.getAlias())
.column(i.getColumnName()).build());
} else if (i.getTableFieldInfo() != null) {
//其次field info
TableFieldInfo info = i.getTableFieldInfo();
if (info.getTypeHandler() != null && info.getTypeHandler() != UnknownTypeHandler.class) {
TypeHandlerRegistry registry = ms.getConfiguration().getTypeHandlerRegistry();
TypeHandler<?> typeHandler = registry.getMappingTypeHandler(info.getTypeHandler());
if (typeHandler == null) {
typeHandler = registry.getInstance(info.getPropertyType(), info.getTypeHandler());
}
resultMappings.add(new ResultMapping.Builder(ms.getConfiguration(), info.getProperty(),
info.getColumn(), info.getPropertyType())
.typeHandler(typeHandler).build());
} else {
resultMappings.add(new ResultMapping.Builder(ms.getConfiguration(), info.getProperty(),
info.getColumn(), info.getPropertyType()).build());
}
} else {
//最后取值
TableFieldInfo info = tableInfo.getFieldList().stream().filter(t -> t.getColumn().equals(i.getColumnName()))
.findFirst().orElseGet(null);
if (info != null && Objects.equals(tableInfo.getKeyColumn(), i.getColumnName())) {
resultMappings.add(new ResultMapping.Builder(ms.getConfiguration(), tableInfo.getKeyProperty(),
tableInfo.getKeyColumn(), tableInfo.getKeyType()).build());
} else if (info != null) {
resultMappings.add(new ResultMapping.Builder(ms.getConfiguration(), info.getProperty(),
info.getColumn(), info.getPropertyType()).build());
} else {
resultMappings.add(new ResultMapping.Builder(ms.getConfiguration(), i.getColumnName())
.column(i.getColumnName()).build());
}
}
});
return new ResultMap.Builder(ms.getConfiguration(), id, resultType, resultMappings).build();
}
if (infoDTO.getTableInfo().isAutoInitResultMap()) {
return ms.getConfiguration().getResultMap(infoDTO.getTableInfo().getResultMap());
}
//TODO 可以加缓存
private ResultMap getDefaultResultMap(TableInfo tableInfo, MappedStatement ms, Class<?> resultType) {
if (tableInfo != null && tableInfo.isAutoInitResultMap()) {
//补充不全的属性
ResultMap resultMap = ms.getConfiguration().getResultMap(tableInfo.getResultMap());
List<ResultMapping> resultMappings = resultMap.getResultMappings();
List<Field> notExistField = ReflectionKit.getFieldList(resultType).stream().filter(i ->
!i.getAnnotation(TableField.class).exist()).collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(notExistField)) {
//复制已有的resultMapping
List<ResultMapping> resultMappingList = new ArrayList<>(resultMappings);
//复制不存在的resultMapping
for (Field i : notExistField) {
resultMappingList.add(new ResultMapping.Builder(ms.getConfiguration(),
i.getName(), i.getName(), i.getType()).build());
}
return new ResultMap.Builder(ms.getConfiguration(), ms.getId(), resultType, resultMappingList).build();
}
}
return new ResultMap.Builder(ms.getConfiguration(), ms.getId(), resultType, EMPTY_RESULT_MAPPING).build();
}

View File

@ -1,4 +1,4 @@
package com.baomidou.mybatisplus.core.metadata;
package com.github.yulichang.mapper;
import com.baomidou.mybatisplus.core.enums.SqlKeyword;

View File

@ -1,6 +1,10 @@
package com.baomidou.mybatisplus.core.metadata;
package com.github.yulichang.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.MPJTableInfoHelper;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.github.yulichang.annotation.EntityMapping;
import com.github.yulichang.annotation.FieldMapping;
@ -22,7 +26,6 @@ import java.util.Map;
* 字段属性
*
* @author yulichang
* @see TableFieldInfo
* @since 1.2.0
*/
@Getter

View File

@ -1,8 +1,7 @@
package com.baomidou.mybatisplus.core.metadata;
package com.github.yulichang.mapper;
import lombok.AccessLevel;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import lombok.Data;
import lombok.Setter;
import lombok.experimental.Accessors;
import java.util.List;
@ -15,7 +14,6 @@ import java.util.List;
* @since 1.2.0
*/
@Data
@Setter(AccessLevel.PACKAGE)
@Accessors(chain = true)
public class MPJTableInfo {

View File

@ -1,4 +1,4 @@
package com.baomidou.mybatisplus.core.metadata;
package com.github.yulichang.mapper;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

View File

@ -9,6 +9,9 @@ import com.github.yulichang.toolkit.Constant;
@SuppressWarnings("unused")
public interface MPJJoin<Children, T> extends MPJBaseJoin<T> {
/**
* left join
*/
default Children leftJoin(String joinSql) {
return leftJoin(true, joinSql);
}
@ -17,6 +20,10 @@ public interface MPJJoin<Children, T> extends MPJBaseJoin<T> {
return join(Constant.LEFT_JOIN, condition, joinSql);
}
/**
* right join
*/
default Children rightJoin(String joinSql) {
return rightJoin(true, joinSql);
}
@ -25,6 +32,10 @@ public interface MPJJoin<Children, T> extends MPJBaseJoin<T> {
return join(Constant.RIGHT_JOIN, condition, joinSql);
}
/**
* inner join
*/
default Children innerJoin(String joinSql) {
return innerJoin(true, joinSql);
}
@ -33,5 +44,16 @@ public interface MPJJoin<Children, T> extends MPJBaseJoin<T> {
return join(Constant.INNER_JOIN, condition, joinSql);
}
/**
* full join
*/
default Children fullJoin(String joinSql) {
return fullJoin(true, joinSql);
}
default Children fullJoin(boolean condition, String joinSql) {
return join(Constant.FULL_JOIN, condition, joinSql);
}
Children join(String keyWord, boolean condition, String joinSql);
}

View File

@ -0,0 +1,71 @@
package com.github.yulichang.toolkit;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
/**
* 查询字段集合
*
* @author yulichang
* @since 1.2.5
*/
public class CacheList<T extends UniqueObject> extends ArrayList<T> implements UniqueObject {
private String uniqueKey;
@Override
public String getUniqueKey() {
if (StringUtils.isBlank(uniqueKey)) {
StringBuilder sb = new StringBuilder();
for (UniqueObject ub : this) {
sb.append(ub.getUniqueKey());
}
this.uniqueKey = sb.toString();
}
return this.uniqueKey;
}
@Override
public boolean add(T t) {
this.uniqueKey = null;
return super.add(t);
}
@Override
public boolean remove(Object o) {
this.uniqueKey = null;
return super.remove(o);
}
@Override
public boolean addAll(Collection<? extends T> c) {
this.uniqueKey = null;
return super.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends T> c) {
this.uniqueKey = null;
return super.addAll(index, c);
}
@Override
public boolean removeAll(Collection<?> c) {
this.uniqueKey = null;
return super.removeAll(c);
}
@Override
protected void removeRange(int fromIndex, int toIndex) {
this.uniqueKey = null;
super.removeRange(fromIndex, toIndex);
}
@Override
public void clear() {
this.uniqueKey = null;
super.clear();
}
}

View File

@ -23,6 +23,8 @@ public interface Constant {
String INNER = "INNER";
String FULL = "FULL";
String CLAZZ = "resultTypeClass_Eg1sG";
String PARAM_TYPE = "paramType_Gr8re1Ee";
@ -42,6 +44,11 @@ public interface Constant {
*/
String INNER_JOIN = StringPool.SPACE + INNER + StringPool.SPACE + JOIN + StringPool.SPACE;
/**
* " FULL JOIN "
*/
String FULL_JOIN = StringPool.SPACE + FULL + StringPool.SPACE + JOIN + StringPool.SPACE;
/**
* " t"
*/

View File

@ -15,6 +15,7 @@ public class SpringContentUtils implements ApplicationContextAware {
private static ApplicationContext context;
@Override
@SuppressWarnings("NullableProblems")
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}

View File

@ -0,0 +1,15 @@
package com.github.yulichang.toolkit;
/**
* 类唯一标识
*
* @author yulichang
* @since 1.2.5
*/
public interface UniqueObject {
/**
* 获取类唯一标识
*/
String getUniqueKey();
}

View File

@ -5,24 +5,22 @@ import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.github.yulichang.toolkit.Constant;
import com.github.yulichang.toolkit.LambdaUtils;
import com.github.yulichang.toolkit.MPJWrappers;
import com.github.yulichang.toolkit.ReflectionKit;
import com.github.yulichang.toolkit.*;
import com.github.yulichang.wrapper.enums.BaseFuncEnum;
import com.github.yulichang.wrapper.interfaces.LambdaJoin;
import com.github.yulichang.wrapper.interfaces.Query;
import com.github.yulichang.wrapper.interfaces.on.OnFunction;
import lombok.Data;
import lombok.Getter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@ -51,11 +49,8 @@ public class MPJLambdaWrapper<T> extends MPJAbstractLambdaWrapper<T, MPJLambdaWr
/**
* 查询的字段
*/
private final List<SelectColumn> selectColumns = new ArrayList<>();
/**
* 忽略查询的字段
*/
private final List<SelectColumn> ignoreColumns = new ArrayList<>();
@Getter
private final List<SelectColumn> selectColumns = new CacheList<>();
/**
* ON sql wrapper集合
*/
@ -68,6 +63,11 @@ public class MPJLambdaWrapper<T> extends MPJAbstractLambdaWrapper<T, MPJLambdaWr
* 是否 select distinct
*/
private boolean selectDistinct = false;
/**
* 是否构建resultMap
*/
@Getter
private boolean resultMap = false;
/**
* 表序号
*/
@ -128,7 +128,7 @@ public class MPJLambdaWrapper<T> extends MPJAbstractLambdaWrapper<T, MPJLambdaWr
public final <S> MPJLambdaWrapper<T> select(SFunction<S, ?>... columns) {
if (ArrayUtils.isNotEmpty(columns)) {
for (SFunction<S, ?> s : columns) {
selectColumns.add(SelectColumn.of(LambdaUtils.getEntityClass(s), getCache(s).getColumn()));
selectColumns.add(SelectColumn.of(LambdaUtils.getEntityClass(s), getCache(s).getColumn(), null));
}
}
return typedThis;
@ -139,7 +139,7 @@ public class MPJLambdaWrapper<T> extends MPJAbstractLambdaWrapper<T, MPJLambdaWr
TableInfo info = TableInfoHelper.getTableInfo(entityClass);
Assert.notNull(info, "table can not be find");
info.getFieldList().stream().filter(predicate).collect(Collectors.toList()).forEach(
i -> selectColumns.add(SelectColumn.of(entityClass, i.getColumn())));
i -> selectColumns.add(SelectColumn.of(entityClass, i.getColumn(), i)));
return typedThis;
}
@ -150,24 +150,24 @@ public class MPJLambdaWrapper<T> extends MPJAbstractLambdaWrapper<T, MPJLambdaWr
List<Field> tagFields = ReflectionKit.getFieldList(tag);
tableInfo.getFieldList().forEach(i -> {
if (tagFields.stream().anyMatch(f -> f.getName().equals(i.getProperty()))) {
selectColumns.add(SelectColumn.of(source, i.getColumn()));
selectColumns.add(SelectColumn.of(source, i.getColumn(), i));
}
});
if (tableInfo.havePK() && tagFields.stream().anyMatch(i -> i.getName().equals(tableInfo.getKeyProperty()))) {
selectColumns.add(SelectColumn.of(source, tableInfo.getKeyProperty()));
selectColumns.add(SelectColumn.of(source, tableInfo.getKeyColumn(), null));
}
return typedThis;
}
@Override
public <S> MPJLambdaWrapper<T> selectAs(SFunction<S, ?> column, String alias) {
selectColumns.add(SelectColumn.of(LambdaUtils.getEntityClass(column), getCache(column).getColumn(), alias));
selectColumns.add(SelectColumn.of(LambdaUtils.getEntityClass(column), getCache(column).getColumn(), null, alias));
return typedThis;
}
public <S> MPJLambdaWrapper<T> selectFunc(boolean condition, BaseFuncEnum funcEnum, SFunction<S, ?> column, String alias) {
if (condition) {
selectColumns.add(SelectColumn.of(LambdaUtils.getEntityClass(column), getCache(column).getColumn(), alias, funcEnum));
selectColumns.add(SelectColumn.of(LambdaUtils.getEntityClass(column), getCache(column).getColumn(), null, alias, funcEnum));
}
return typedThis;
}
@ -175,7 +175,7 @@ public class MPJLambdaWrapper<T> extends MPJAbstractLambdaWrapper<T, MPJLambdaWr
@Override
public MPJLambdaWrapper<T> selectFunc(boolean condition, BaseFuncEnum funcEnum, Object column, String alias) {
if (condition) {
selectColumns.add(SelectColumn.of(null, column.toString(), alias, funcEnum));
selectColumns.add(SelectColumn.of(null, column.toString(), null, alias, funcEnum));
}
return typedThis;
}
@ -184,21 +184,10 @@ public class MPJLambdaWrapper<T> extends MPJAbstractLambdaWrapper<T, MPJLambdaWr
TableInfo info = TableInfoHelper.getTableInfo(clazz);
Assert.notNull(info, "table can not be find -> %s", clazz);
if (info.havePK()) {
selectColumns.add(SelectColumn.of(clazz, info.getKeyColumn()));
selectColumns.add(SelectColumn.of(clazz, info.getKeyColumn(), null));
}
info.getFieldList().forEach(c ->
selectColumns.add(SelectColumn.of(clazz, c.getColumn())));
return typedThis;
}
@Override
@SafeVarargs
public final <S> MPJLambdaWrapper<T> selectIgnore(SFunction<S, ?>... columns) {
if (ArrayUtils.isNotEmpty(columns)) {
for (SFunction<S, ?> s : columns) {
ignoreColumns.add(SelectColumn.of(LambdaUtils.getEntityClass(s), getCache(s).getColumn()));
}
}
selectColumns.add(SelectColumn.of(clazz, c.getColumn(), c)));
return typedThis;
}
@ -208,10 +197,6 @@ public class MPJLambdaWrapper<T> extends MPJAbstractLambdaWrapper<T, MPJLambdaWr
@Override
public String getSqlSelect() {
if (StringUtils.isBlank(sqlSelect.getStringValue())) {
if (CollectionUtils.isNotEmpty(ignoreColumns)) {
selectColumns.removeIf(c -> c.getFuncEnum() == null && ignoreColumns.stream().anyMatch(i ->
i.getClazz() == c.getClazz() && Objects.equals(c.getColumnName(), i.getColumnName())));
}
String s = selectColumns.stream().map(i -> {
String str = Constant.TABLE_ALIAS + getDefault(subTable.get(i.getClazz())) + StringPool.DOT + i.getColumnName();
return (i.getFuncEnum() == null ? str : String.format(i.getFuncEnum().getSql(), str)) +
@ -272,7 +257,6 @@ public class MPJLambdaWrapper<T> extends MPJAbstractLambdaWrapper<T, MPJLambdaWr
sqlSelect.toNull();
from.toNull();
selectColumns.clear();
ignoreColumns.clear();
subTable.clear();
}
@ -286,55 +270,4 @@ public class MPJLambdaWrapper<T> extends MPJAbstractLambdaWrapper<T, MPJLambdaWr
}
return typedThis;
}
/**
* select字段
*/
@Data
private static class SelectColumn {
/**
* 字段实体类
*/
private Class<?> clazz;
/**
* 数据库字段名
*/
private String columnName;
/**
* 字段别名
*/
private String alias;
/**
* 字段函数
*/
private BaseFuncEnum funcEnum;
/**
* 自定义函数填充参数
*/
private List<SFunction<?, ?>> funcArgs;
private SelectColumn(Class<?> clazz, String columnName, String alias, BaseFuncEnum funcEnum) {
this.clazz = clazz;
this.columnName = columnName;
this.alias = alias;
this.funcEnum = funcEnum;
}
public static SelectColumn of(Class<?> clazz, String columnName) {
return new SelectColumn(clazz, columnName, null, null);
}
public static SelectColumn of(Class<?> clazz, String columnName, String alias) {
return new SelectColumn(clazz, columnName, alias, null);
}
public static SelectColumn of(Class<?> clazz, String columnName, String alias, BaseFuncEnum funcEnum) {
return new SelectColumn(clazz, columnName, alias, funcEnum);
}
}
}

View File

@ -0,0 +1,74 @@
package com.github.yulichang.wrapper;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.github.yulichang.toolkit.UniqueObject;
import com.github.yulichang.wrapper.enums.BaseFuncEnum;
import lombok.Data;
import java.util.Objects;
/**
* MPJLambdaWrapper 查询字段
*
* @author yulichang
* @since 1.2.5
*/
@Data
public class SelectColumn implements UniqueObject {
/**
* 字段实体类
*/
private Class<?> clazz;
/**
* 数据库字段名
*/
private String columnName;
/**
* 字段信息
*/
private TableFieldInfo tableFieldInfo;
/**
* 字段别名
*/
private String alias;
/**
* 字段函数
*/
private BaseFuncEnum funcEnum;
private SelectColumn(Class<?> clazz, String columnName, TableFieldInfo tableFieldInfo, String alias, BaseFuncEnum funcEnum) {
this.clazz = clazz;
this.columnName = columnName;
this.tableFieldInfo = tableFieldInfo;
this.alias = alias;
this.funcEnum = funcEnum;
}
public static SelectColumn of(Class<?> clazz, String columnName, TableFieldInfo tableFieldInfo) {
return new SelectColumn(clazz, columnName, tableFieldInfo, null, null);
}
public static SelectColumn of(Class<?> clazz, String columnName, TableFieldInfo tableFieldInfo, String alias) {
return new SelectColumn(clazz, columnName, tableFieldInfo, alias, null);
}
public static SelectColumn of(Class<?> clazz, String columnName, TableFieldInfo tableFieldInfo, String alias, BaseFuncEnum funcEnum) {
return new SelectColumn(clazz, columnName, tableFieldInfo, alias, funcEnum);
}
/**
* 获取唯一标识
*/
@Override
public String getUniqueKey() {
return String.join(StringPool.AMPERSAND, clazz.getName(), columnName, alias,
Objects.isNull(funcEnum) ? null : funcEnum.getSql());
}
}

View File

@ -111,20 +111,6 @@ public interface Query<Children> extends Serializable {
return selectFunc(condition, funcEnum, column, LambdaUtils.getName(alias));
}
/**
* 忽略查询字段
* <p>
* 用法: selectIgnore(UserDO::getId,UserDO::getSex)
* 注意: 一个selectIgnore只支持一个对象 如果要忽略多个实体的字段,请调用多次
* <p>
* .selectIgnore(UserDO::getId,UserDO::getSex)
* .selectIgnore(UserAddressDO::getArea,UserAddressDO::getCity)
*
* @since 1.1.3
*/
@SuppressWarnings("unchecked")
<S> Children selectIgnore(SFunction<S, ?>... columns);
/**
* 查询实体类全部字段
*/