feat: aos-mybatis-plus

This commit is contained in:
wyl
2022-07-26 23:35:09 +08:00
parent 165b390e79
commit f899392619
4 changed files with 252 additions and 6 deletions
+2
View File
@@ -1,2 +1,4 @@
/.idea/
**.iml
**/logs
**/target
+23 -6
View File
@@ -3,17 +3,34 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>aos-core</artifactId>
<artifactId>aos-dependencies</artifactId>
<groupId>com.aos</groupId>
<version>1.0-SNAPSHOT</version>
<relativePath>../aos-dependencies/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>aos-mybatis-plus</artifactId>
<properties>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,69 @@
package com.aos.mybatis.plus.conf;
import com.aos.mybatis.plus.interceptor.MybatisSqlCompletePrintInterceptor;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusPropertiesCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author: wangyl
* @date: 2022/7/26
* @description: mybatis-plus配置
*/
@Configuration
public class MybatisPlusConf {
/**
* mybatis的SQL格式化和耗时打印
*
* @return com.aos.common.interceptor.MybatisSqlCompletePrintInterceptor
* @Date 2022/1/12 23:44
* @Author wangyl
* @Version V1.0
*/
@Bean
@ConditionalOnClass(org.apache.ibatis.plugin.Interceptor.class)
MybatisSqlCompletePrintInterceptor mybatisSqlCompletePrintInterceptor() {
return new MybatisSqlCompletePrintInterceptor();
}
/**
* mybatis plus 分页插件加载 mysql
*
* @return com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor
* @Date 2022/1/12 23:44
* @Author wangyl
* @Version V1.0
*/
@Bean
@ConditionalOnMissingBean(com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor.class)
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
/**
* mybatis plus 逻辑删除配置
*
* @return com.baomidou.mybatisplus.autoconfigure.MybatisPlusPropertiesCustomizer
* @Date 2022/1/12 23:45
* @Author wangyl
* @Version V1.0
*/
@Bean
@ConditionalOnClass(com.baomidou.mybatisplus.autoconfigure.MybatisPlusPropertiesCustomizer.class)
@ConditionalOnMissingBean(com.baomidou.mybatisplus.autoconfigure.MybatisPlusPropertiesCustomizer.class)
public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {
return plusProperties -> plusProperties.getGlobalConfig()
.getDbConfig()
.setLogicDeleteField("deleted")
.setLogicDeleteValue("1")
.setLogicNotDeleteValue("0");
}
}
@@ -0,0 +1,158 @@
package com.aos.mybatis.plus.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.core.Ordered;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}), @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}), @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})})
@Slf4j
public class MybatisSqlCompletePrintInterceptor implements Interceptor, Ordered {
private Configuration configuration = null;
/**
* 时间格式处理
*/
private static final ThreadLocal<SimpleDateFormat> DATE_FORMAT_THREAD_LOCAL = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
@Override
public Object intercept(Invocation invocation) throws Throwable {
long startTime = System.currentTimeMillis();
try {
return invocation.proceed();
} finally {
if (log.isDebugEnabled()) {
Object target = invocation.getTarget();
String sql = this.getSql(target);
long endTime = System.currentTimeMillis();
long sqlCost = endTime - startTime;
log.debug("执行的sql为:{}", sql);
log.debug("执行耗时为:{}", sqlCost);
}
}
}
/**
* 获取sql
*
* @param target
* @return
* @throws IllegalAccessException
*/
private String getSql(Object target) {
try {
StatementHandler statementHandler = (StatementHandler) target;
BoundSql boundSql = statementHandler.getBoundSql();
if (configuration == null) {
ParameterHandler parameterHandler = statementHandler.getParameterHandler();
Field configurationField = ReflectionUtils.findField(parameterHandler.getClass(), "configuration");
ReflectionUtils.makeAccessible(configurationField);
this.configuration = (Configuration) configurationField.get(parameterHandler);
}
//替换参数格式化Sql语句,去除换行符
return formatSql(boundSql, configuration);
} catch (Exception e) {
log.warn("get sql error {}", target, e);
}
return "";
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
/**
* 获取完整的sql实体的信息
*
* @param boundSql
* @return
*/
private String formatSql(BoundSql boundSql, Configuration configuration) {
String sql = boundSql.getSql();
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
Object parameterObject = boundSql.getParameterObject();
// 输入sql字符串空判断
if (sql == null || sql.length() == 0) {
return "";
}
if (configuration == null) {
return "";
}
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
// 美化sql
sql = beautifySql(sql);
/**
* @see org.apache.ibatis.scripting.defaults.DefaultParameterHandler 参考Mybatis 参数处理
*/
if (parameterMappings != null) {
for (ParameterMapping parameterMapping : parameterMappings) {
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
if (boundSql.hasAdditionalParameter(propertyName)) {
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
value = metaObject.getValue(propertyName);
}
String paramValueStr = "";
if (value instanceof String) {
paramValueStr = "'" + value + "'";
} else if (value instanceof Date) {
paramValueStr = "'" + DATE_FORMAT_THREAD_LOCAL.get()
.format(value) + "'";
} else {
paramValueStr = value + "";
}
sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(paramValueStr));
}
}
}
return sql;
}
/**
* 美化Sql
*/
private String beautifySql(String sql) {
sql = sql.replaceAll("[\\s\n ]+", " ");
return sql;
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}