Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

改进部分代码细节,提高运行性能 #6593

Open
wants to merge 4 commits into
base: 3.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,12 @@ public <T> void removeMapper(Class<T> type) {
// 清空 Mapper 方法 mappedStatement 缓存信息
String typeKey = type.getName() + StringPool.DOT;
String simpleName = type.getSimpleName();
mappedStatements.keySet().stream().filter(ms -> ms.startsWith(typeKey) || ms.equals(simpleName)).collect(Collectors.toSet()).forEach(mappedStatements::remove);
resultMaps.keySet().stream().filter(r -> r.startsWith(typeKey)).collect(Collectors.toSet()).forEach(resultMaps::remove);
parameterMaps.keySet().stream().filter(p -> p.startsWith(typeKey)).collect(Collectors.toSet()).forEach(parameterMaps::remove);
keyGenerators.keySet().stream().filter(k -> k.startsWith(typeKey)).collect(Collectors.toSet()).forEach(keyGenerators::remove);
sqlFragments.keySet().stream().filter(s -> s.startsWith(typeKey)).collect(Collectors.toSet()).forEach(sqlFragments::remove);
caches.keySet().stream().filter(p -> p.equals(type.getName()) || p.equals(simpleName)).collect(Collectors.toSet()).forEach(caches::remove);
mappedStatements.keySet().stream().filter(ms -> ms.startsWith(typeKey) || ms.equals(simpleName)).forEach(mappedStatements::remove);
resultMaps.keySet().stream().filter(r -> r.startsWith(typeKey)).forEach(resultMaps::remove);
parameterMaps.keySet().stream().filter(p -> p.startsWith(typeKey)).forEach(parameterMaps::remove);
keyGenerators.keySet().stream().filter(k -> k.startsWith(typeKey)).forEach(keyGenerators::remove);
sqlFragments.keySet().stream().filter(s -> s.startsWith(typeKey)).forEach(sqlFragments::remove);
caches.keySet().stream().filter(p -> p.equals(type.getName()) || p.equals(simpleName)).forEach(caches::remove);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,10 @@ public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
// fix https://github.com/baomidou/mybatis-plus/issues/4247
MybatisMapperProxyFactory<T> mapperProxyFactory = (MybatisMapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
mapperProxyFactory = (MybatisMapperProxyFactory<T>) knownMappers.entrySet().stream()
.filter(t -> t.getKey().getName().equals(type.getName())).findFirst().map(Map.Entry::getValue)
.orElseThrow(() -> new BindingException("Type " + type + " is not known to the MybatisPlusMapperRegistry."));
mapperProxyFactory = findByName(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MybatisPlusMapperRegistry.");
}
}
try {
return mapperProxyFactory.newInstance(sqlSession);
Expand All @@ -60,6 +61,15 @@ public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
}
}

private <T> MybatisMapperProxyFactory<T> findByName(Class<T> type) {
for (Map.Entry<Class<?>, MybatisMapperProxyFactory<?>> entry : knownMappers.entrySet()) {
if (entry.getKey().getName().equals(type.getName())) {
return (MybatisMapperProxyFactory<T>) entry.getValue();
}
}
return null;
}

@Override
public <T> boolean hasMapper(Class<T> type) {
return knownMappers.containsKey(type);
Expand All @@ -69,8 +79,9 @@ public <T> boolean hasMapper(Class<T> type) {
* 清空 Mapper 缓存信息
*/
protected <T> void removeMapper(Class<T> type) {
knownMappers.entrySet().stream().filter(t -> t.getKey().getName().equals(type.getName()))
.findFirst().ifPresent(t -> knownMappers.remove(t.getKey()));
if (findByName(type) != null) {
knownMappers.remove(type);
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,12 +205,12 @@ private Collection<Object> extractParameters(Object parameterObject) {
Collection<Object> parameters = new ArrayList<>();
Map<String, Object> parameterMap = (Map) parameterObject;
Set<Object> objectSet = new HashSet<>();
parameterMap.forEach((k, v) -> {
for (Object v : parameterMap.values()) {
if (objectSet.add(v)) {
Collection<Object> collection = toCollection(v);
parameters.addAll(collection);
}
});
}
return parameters;
} else {
return Collections.singleton(parameterObject);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,33 +110,31 @@ public Children setEntityClass(Class<T> entityClass) {
@Override
public <V> Children allEq(boolean condition, Map<R, V> params, boolean null2IsNull) {
if (condition && CollectionUtils.isNotEmpty(params)) {
params.forEach((k, v) -> {
if (StringUtils.checkValNotNull(v)) {
eq(k, v);
} else {
if (null2IsNull) {
isNull(k);
}
for (Map.Entry<R, V> entry : params.entrySet()) {
if (StringUtils.checkValNotNull(entry.getValue())) {
eq(entry.getKey(), entry.getValue());
} else if (null2IsNull) {
isNull(entry.getKey());
}
});
}
}
return typedThis;
}

@Override
public <V> Children allEq(boolean condition, BiPredicate<R, V> filter, Map<R, V> params, boolean null2IsNull) {
if (condition && CollectionUtils.isNotEmpty(params)) {
params.forEach((k, v) -> {
for (Map.Entry<R, V> entry : params.entrySet()) {
R k = entry.getKey();
V v = entry.getValue();
if (filter.test(k, v)) {
if (StringUtils.checkValNotNull(v)) {
eq(k, v);
} else {
if (null2IsNull) {
isNull(k);
}
} else if (null2IsNull) {
isNull(k);
}
}
});
}
}
return typedThis;
}
Expand Down Expand Up @@ -374,16 +372,16 @@ public Children doGroupBy(boolean condition, R column, List<R> columns) {
});
}


public Children doOrderBy(boolean condition, boolean isAsc, R column, List<R> columns) {
return maybeDo(condition, () -> {
final SqlKeyword mode = isAsc ? ASC : DESC;
if (column != null) {
appendSqlSegments(ORDER_BY, columnToSqlSegment(column), mode);
}
if (CollectionUtils.isNotEmpty(columns)) {
columns.forEach(c -> appendSqlSegments(ORDER_BY,
columnToSqlSegment(c), mode));
for (R c : columns) {
appendSqlSegments(ORDER_BY, columnToSqlSegment(c), mode);
}
}
});
}
Expand Down Expand Up @@ -416,8 +414,11 @@ public Children orderBy(boolean condition, boolean isAsc, R column) {

@Override
public Children orderBy(boolean condition, boolean isAsc, List<R> columns) {
return maybeDo(condition, () -> columns.forEach(c -> appendSqlSegments(ORDER_BY,
columnToSqlSegment(c), isAsc ? ASC : DESC)));
return maybeDo(condition, () -> {
for (R c : columns) {
appendSqlSegments(ORDER_BY, columnToSqlSegment(c), isAsc ? ASC : DESC);
}
});
}

@Override
Expand Down Expand Up @@ -578,7 +579,7 @@ protected ISqlSegment inExpression(Object[] values) {
*/
protected void initNeed() {
paramNameSeq = new AtomicInteger(0);
paramNameValuePairs = new HashMap<>(16);
paramNameValuePairs = new HashMap<>();
expression = new MergeSegments();
lastSql = SharedString.emptyString();
sqlComment = SharedString.emptyString();
Expand Down Expand Up @@ -707,5 +708,7 @@ public Children clone() {
public interface DoSomething {

void doIt();

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
*/
package com.baomidou.mybatisplus.core.enums;

import java.util.ArrayList;
import java.util.List;

/**
* MybatisPlus 支持 SQL 方法
*
Expand Down Expand Up @@ -101,6 +104,8 @@ public enum SqlMethod {
private final String method;
private final String desc;
private final String sql;
/** [ null, [s1From, s1To], null, null, [s2From, s2To] ] */
private transient int[][] compiledPosPairs;

SqlMethod(String method, String desc, String sql) {
this.method = method;
Expand All @@ -119,4 +124,43 @@ public String getDesc() {
public String getSql() {
return sql;
}

private static int[][] compile(final String sqlTemplate) {
final List<int[]> list = new ArrayList<>(6);
final String placeholder = "%s";
int begin = 0, pos = sqlTemplate.indexOf(placeholder, begin);
while (pos != -1) {
if (begin < pos) {
list.add(new int[] { begin, pos });
}
list.add(null); // null is placeholder
begin = pos + placeholder.length();
pos = sqlTemplate.indexOf(placeholder, begin);
}
final int length = sqlTemplate.length();
if (begin < length) {
list.add(new int[] { begin, length });
}
return list.toArray(new int[list.size()][]);
}

public String format(Object... args) {
// return String.format(getSql(), args);
int[][] pairs = compiledPosPairs;
final String sql = getSql();
if (pairs == null) {
compiledPosPairs = pairs = compile(sql);
}
final StringBuilder sb = new StringBuilder(sql.length() + 64);
int i = 0;
for (final int[] pair : pairs) {
if (pair == null) {
sb.append(args[i++]);
} else {
sb.append(sql, pair[0], pair[1]);
}
}
return sb.toString();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@
*/
package com.baomidou.mybatisplus.core.handlers;

import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.metadata.*;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;

Expand Down Expand Up @@ -194,14 +193,17 @@ default MetaObjectHandler strictUpdateFill(TableInfo tableInfo, MetaObject metaO
*/
default MetaObjectHandler strictFill(boolean insertFill, TableInfo tableInfo, MetaObject metaObject, List<StrictFill<?, ?>> strictFills) {
if ((insertFill && tableInfo.isWithInsertFill()) || (!insertFill && tableInfo.isWithUpdateFill())) {
strictFills.forEach(i -> {
for (StrictFill<?, ?> i : strictFills) {
final String fieldName = i.getFieldName();
final Class<?> fieldType = i.getFieldType();
tableInfo.getFieldList().stream()
.filter(j -> j.getProperty().equals(fieldName) && fieldType.equals(j.getPropertyType()) &&
((insertFill && j.isWithInsertFill()) || (!insertFill && j.isWithUpdateFill()))).findFirst()
.ifPresent(j -> strictFillStrategy(metaObject, fieldName, i.getFieldVal()));
});
for (TableFieldInfo j : tableInfo.getFieldList()) {
if (j.getProperty().equals(fieldName) && fieldType.equals(j.getPropertyType()) &&
((insertFill && j.isWithInsertFill()) || (!insertFill && j.isWithUpdateFill()))) {
strictFillStrategy(metaObject, fieldName, i.getFieldVal());
break;
}
}
}
}
return this;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,9 @@ public void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapp
}
if (CollectionUtils.isNotEmpty(methodList)) {
// 循环注入自定义方法
methodList.forEach(m -> m.inject(builderAssistant, mapperClass, modelClass, tableInfo));
for (AbstractMethod m : methodList) {
m.inject(builderAssistant, mapperClass, modelClass, tableInfo);
}
} else {
logger.debug(className + ", No effective injection method was found.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,14 @@ public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> mode
String sql;
SqlMethod sqlMethod = SqlMethod.LOGIC_DELETE;
if (tableInfo.isWithLogicDelete()) {
sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlLogicSet(tableInfo),
sql = sqlMethod.format(tableInfo.getTableName(), sqlLogicSet(tableInfo),
sqlWhereEntityWrapper(true, tableInfo),
sqlComment());
SqlSource sqlSource = super.createSqlSource(configuration, sql, modelClass);
return addUpdateMappedStatement(mapperClass, modelClass, methodName, sqlSource);
} else {
sqlMethod = SqlMethod.DELETE;
sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(),
sql = sqlMethod.format(tableInfo.getTableName(),
sqlWhereEntityWrapper(true, tableInfo),
sqlComment());
SqlSource sqlSource = super.createSqlSource(configuration, sql, modelClass);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,18 @@ public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> mode
String sqlSet = "SET " + SqlScriptUtils.convertIf(fieldInfos.stream()
.map(i -> i.getSqlSet(EMPTY)).collect(joining(EMPTY)), "[email protected]@isSimpleType(_parameter.getClass())", true)
+ tableInfo.getLogicDeleteSql(false, false);
sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlSet, tableInfo.getKeyColumn(),
sql = sqlMethod.format(tableInfo.getTableName(), sqlSet, tableInfo.getKeyColumn(),
tableInfo.getKeyProperty(), tableInfo.getLogicDeleteSql(true, true));
} else {
sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlLogicSet(tableInfo),
sql = sqlMethod.format(tableInfo.getTableName(), sqlLogicSet(tableInfo),
tableInfo.getKeyColumn(), tableInfo.getKeyProperty(),
tableInfo.getLogicDeleteSql(true, true));
}
SqlSource sqlSource = super.createSqlSource(configuration, sql, Object.class);
return addUpdateMappedStatement(mapperClass, modelClass, methodName, sqlSource);
} else {
sqlMethod = SqlMethod.DELETE_BY_ID;
sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), tableInfo.getKeyColumn(),
sql = sqlMethod.format(tableInfo.getTableName(), tableInfo.getKeyColumn(),
tableInfo.getKeyProperty());
return this.addDeleteMappedStatement(mapperClass, methodName, super.createSqlSource(configuration, sql, Object.class));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> mode
return addUpdateMappedStatement(mapperClass, modelClass, methodName, sqlSource);
} else {
sqlMethod = SqlMethod.DELETE_BY_IDS;
sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), tableInfo.getKeyColumn(),
sql = sqlMethod.format(tableInfo.getTableName(), tableInfo.getKeyColumn(),
SqlScriptUtils.convertForeach(
SqlScriptUtils.convertChoose("@org.apache.ibatis.type.SimpleTypeRegistry@isSimpleType(item.getClass())",
"#{item}", "#{item." + tableInfo.getKeyProperty() + "}"),
Expand All @@ -88,7 +88,7 @@ public String logicDeleteScript(TableInfo tableInfo, SqlMethod sqlMethod) {
.map(i -> i.getSqlSet(Constants.MP_FILL_ET + StringPool.DOT)).collect(joining(EMPTY)), String.format("%s != null", Constants.MP_FILL_ET), true);
}
sqlSet += StringPool.EMPTY + tableInfo.getLogicDeleteSql(false, false);
return String.format(sqlMethod.getSql(), tableInfo.getTableName(),
return sqlMethod.format(tableInfo.getTableName(),
sqlSet, tableInfo.getKeyColumn(), SqlScriptUtils.convertForeach(
SqlScriptUtils.convertChoose("@org.apache.ibatis.type.SimpleTypeRegistry@isSimpleType(item.getClass())",
"#{item}", "#{item." + tableInfo.getKeyProperty() + "}"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@ public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> mode
String sql;
SqlMethod sqlMethod = SqlMethod.LOGIC_DELETE_BY_MAP;
if (tableInfo.isWithLogicDelete()) {
sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlLogicSet(tableInfo), sqlWhereByMap(tableInfo));
sql = sqlMethod.format(tableInfo.getTableName(), sqlLogicSet(tableInfo), sqlWhereByMap(tableInfo));
SqlSource sqlSource = super.createSqlSource(configuration, sql, Map.class);
return addUpdateMappedStatement(mapperClass, Map.class, methodName, sqlSource);
} else {
sqlMethod = SqlMethod.DELETE_BY_MAP;
sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), this.sqlWhereByMap(tableInfo));
sql = sqlMethod.format(tableInfo.getTableName(), this.sqlWhereByMap(tableInfo));
SqlSource sqlSource = super.createSqlSource(configuration, sql, Map.class);
return this.addDeleteMappedStatement(mapperClass, methodName, sqlSource);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> mode
keyColumn = tableInfo.getKeyColumn();
}
}
String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), columnScript, valuesScript);
String sql = sqlMethod.format(tableInfo.getTableName(), columnScript, valuesScript);
SqlSource sqlSource = super.createSqlSource(configuration, sql, modelClass);
return this.addInsertMappedStatement(mapperClass, modelClass, methodName, sqlSource, keyGenerator, keyProperty, keyColumn);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public SelectById(String name) {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
SqlMethod sqlMethod = SqlMethod.SELECT_BY_ID;
SqlSource sqlSource = super.createSqlSource(configuration, String.format(sqlMethod.getSql(),
SqlSource sqlSource = super.createSqlSource(configuration, sqlMethod.format(
sqlSelectColumns(tableInfo, false),
tableInfo.getTableName(), tableInfo.getKeyColumn(), tableInfo.getKeyProperty(),
tableInfo.getLogicDeleteSql(true, true)), Object.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public SelectByIds(String name) {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
SqlMethod sqlMethod = SqlMethod.SELECT_BY_IDS;
SqlSource sqlSource = super.createSqlSource(configuration, String.format(sqlMethod.getSql(),
SqlSource sqlSource = super.createSqlSource(configuration, sqlMethod.format(
sqlSelectColumns(tableInfo, false), tableInfo.getTableName(), tableInfo.getKeyColumn(),
SqlScriptUtils.convertForeach("#{item}", COLL, null, "item", COMMA),
tableInfo.getLogicDeleteSql(true, true)), Object.class);
Expand Down
Loading