背景:需要分表的情況下 不借助中間件 如何實(shí)現(xiàn)管理后臺(tái)頁(yè)面的多表聚合查詢爵憎?
想法是通過mybatis 提供的攔截器 重寫sql
package com.jdh.general.config;
import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import com.jdh.general.common.annotation.CallWhen;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* 單庫(kù)分表 做聚合查詢 攔截器
*
* @author hubin
* @since 2016-08-16
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Accessors(chain = true)
@Intercepts({@Signature(type = Executor.class, method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class SimpleUnionQuery extends AbstractSqlParserHandler implements Interceptor {
@SuppressWarnings("unused")
private static final Log logger = LogFactory.getLog(SimpleUnionQuery .class);
private Properties properties;
final static String _FROM = " FROM ";
final static String _WHERE = " WHERE ";
final static String _LIMIT = " LIMIT ";
/**
* intercept 方法用來對(duì)攔截的sql進(jìn)行具體的操作
*
* @param invocation
* @return
* @throws Throwable
*/
@Override
public Object intercept(Invocation invocation) throws Throwable {
Method method = invocation.getMethod();
//由自定義注解配置
CallWhen annotation = method.getAnnotation(CallWhen.class);
ArrayList<String> tableNums = new ArrayList<>();
tableNums.add("_1");
tableNums.add("_2");
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameterObject = args[1];
BoundSql boundSql = ms.getBoundSql(parameterObject);
String origSql = boundSql.getSql();
//多少個(gè)union all 表構(gòu)建多少次參數(shù)
List<ParameterMapping> tempParam = boundSql.getParameterMappings();
tableNums.forEach(tableNum->{
boundSql.getParameterMappings().addAll(tempParam);
});
// 組裝新的 sql
String newSql = sqlUpdate(origSql,tableNums);
// 重新new一個(gè)查詢語(yǔ)句對(duì)象
BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql,
boundSql.getParameterMappings(), boundSql.getParameterObject());
// 把新的查詢放到statement里
MappedStatement newMs = newMappedStatement(ms, new BoundSqlSqlSource(newBoundSql));
for (ParameterMapping mapping : boundSql.getParameterMappings()) {
String prop = mapping.getProperty();
if (boundSql.hasAdditionalParameter(prop)) {
newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
}
}
Object[] queryArgs = invocation.getArgs();
queryArgs[0] = newMs;
return invocation.proceed();
}
/**
*
* @param sql 源sql
* @param tableNums 需要構(gòu)建表名個(gè)數(shù)
* @return
*/
public String sqlUpdate(String sql, ArrayList<String> tableNums) {
String[] froms = sql.split(_FROM);
String column = froms[0];
String fromAfter = froms[1];
String[] wheres = fromAfter.split(_WHERE);
String table = wheres[0];
String whereAfter = wheres[1];
String[] limits = whereAfter.split(_LIMIT);
String condition = limits[0];
String limit = limits[1];
StringBuilder sqlContent = new StringBuilder();
for (int i = 0; i < tableNums.size(); i++) {
sqlContent.append(column)
.append(_FROM)
.append(table.trim() + tableNums.get(i))
.append(_WHERE)
.append(condition);
if ((i + 1) < tableNums.size()) sqlContent.append(" UNION All \n");
}
sqlContent.append(_LIMIT).append(limit);
return sqlContent.toString();
}
/**
* 定義一個(gè)內(nèi)部輔助類,作用是包裝 SQL
*/
class BoundSqlSqlSource implements SqlSource {
private BoundSql boundSql;
public BoundSqlSqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
}
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
}
private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
MappedStatement.Builder builder = new
MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
builder.keyProperty(ms.getKeyProperties()[0]);
}
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.resultSetType(ms.getResultSetType());
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
return builder.build();
}
@Override
public Object plugin(Object target) {
if (target instanceof Executor) {
return Plugin.wrap(target, this);
}
return target;
}
@Override
public void setProperties(Properties prop) {
this.properties = prop;
}