序文
ps:先日3100の防衛に参加させていただきました、とても熾烈な戦いでした、たった今戦いを終えました、書きかけのブログを更新させてください。
この記事は、毎日のクエリの作成、動的条件 SQL の簡単なパッケージの作成、およびそれを自動生成することを目的としています (レンガを投げて翡翠を引き寄せる、小さなおもちゃを作る、気に入らない場合はスプレーしないでください) )。
文章
私たちが通常作成するクエリを見てみましょう。基本的には動的 SQL を作成します。
フィールドに if を書きます。それが面倒だと思う人はいますか。
各テーブルのクエリの多くにはこの種の要件があり、どのクエリに応じて、空でない場合に条件がトリガーされます。
毎日書いて毎日書いて、コピーして変更して、コピーして変更して、それが面倒だと思う人はいますか。
これを見て、プラグインを使用して自動的に生成すればよいと言う人もいるかもしれません。
裁判官の中には、mybatis-plus を使えばいいと言う人もいるでしょう。
それは当然ですが、私はただ小さなおもちゃ全体が欲しいだけです。私を放っておいて。
全体を開く
この記事で実装した小さなおもちゃのカプセル化のアイデア:
①ルールの策定(カスタム アノテーション @JcSqlQuery のマーキングや、JcDynamics による関数の名前付けなど)。
② トリガーされたクエリがルールを満たしている場合、渡されたパラメータ オブジェクトが空でない場合は、そのパラメータに従って SQL クエリ条件が自動的に組み立てられます。
③ mybatis @Select アノテーションを使用してデフォルトのテーブルクエリ SQL を記述し、ついでにカスタム mybatis インターセプタを入力します。
④SQLを組み立てたら実行して完了です。
最初にマッパー関数を作成します。
/**
* @Author JCccc
* @Description
* @Date 2023/12/14 16:56
*/
@Mapper
public interface DistrictMapper {
@Select("select code,name,parent_code,full_name FROM s_district_info")
List<District> queryListJcDynamics(District district);
@Select("select code,name,parent_code,full_name FROM s_district_info")
District queryOneJcDynamics(District district);
}
次に、ParamClassInfo.java を使用して、動的 SQL アセンブリに参加する必要があるクラスを収集します。
import lombok.Data;
/**
* @Author JCccc
* @Description
* @Date 2021/12/14 16:56
*/
@Data
public class ParamClassInfo {
private String classType;
private Object keyValue;
private String keyName;
}
次に、カスタムの mybatis インターセプターがあります (自己アセンブリを実現するためにいくつかの小さな関数がここに書かれています。以下に図があります)。
MybatisInterceptor.java
import com.example.dotest.entity.ParamClassInfo;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.*;
/**
* @Author JCccc
* @Description
* @Date 2021/12/14 16:56
*/
@Component
@Intercepts({
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class MybatisInterceptor implements Interceptor {
private final static String JC_DYNAMICS = "JcDynamics";
@Override
public Object intercept(Invocation invocation) throws Throwable {
//获取执行参数
Object[] objects = invocation.getArgs();
MappedStatement ms = (MappedStatement) objects[0];
Object objectParam = objects[1];
List<ParamClassInfo> paramClassInfos = convertParamList(objectParam);
String queryConditionSqlScene = getQueryConditionSqlScene(paramClassInfos);
//解析执行sql的map方法,开始自定义规则匹配逻辑
String mapperMethodAllName = ms.getId();
int lastIndex = mapperMethodAllName.lastIndexOf(".");
String mapperClassStr = mapperMethodAllName.substring(0, lastIndex);
String mapperClassMethodStr = mapperMethodAllName.substring((lastIndex + 1));
Class<?> mapperClass = Class.forName(mapperClassStr);
Method[] methods = mapperClass.getMethods();
for (Method method : methods) {
if (method.getName().equals(mapperClassMethodStr) && mapperClassMethodStr.contains(JC_DYNAMICS)) {
BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
String originalSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ");
//进行自动的 条件拼接
String newSql = originalSql + queryConditionSqlScene;
BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql,
boundSql.getParameterMappings(), boundSql.getParameterObject());
MappedStatement newMs = newMappedStatement(ms, new MyBoundSqlSqlSource(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;
System.out.println("打印新SQL语句" + newSql);
}
}
//继续执行逻辑
return invocation.proceed();
}
private String getQueryConditionSqlScene(List<ParamClassInfo> paramClassInfos) {
StringBuilder conditionParamBuilder = new StringBuilder();
if (CollectionUtils.isEmpty(paramClassInfos)) {
return "";
}
conditionParamBuilder.append(" WHERE ");
int size = paramClassInfos.size();
for (int index = 0; index < size; index++) {
ParamClassInfo paramClassInfo = paramClassInfos.get(index);
String keyName = paramClassInfo.getKeyName();
//默认驼峰拆成下划线 ,比如 userName -》 user_name , name -> name
//如果是需要取别名,其实可以加上自定义注解这些,但是本篇例子是轻封装,思路给到,你们i自己玩
String underlineKeyName = camelToUnderline(keyName);
conditionParamBuilder.append(underlineKeyName);
Object keyValue = paramClassInfo.getKeyValue();
String classType = paramClassInfo.getClassType();
//其他类型怎么处理 ,可以按照类型区分 ,比如检测到一组开始时间,Date 拼接 between and等
// if (classType.equals("String")){
// conditionParamBuilder .append("=").append("\'").append(keyValue).append("\'");
// }
conditionParamBuilder.append("=").append("\'").append(keyValue).append("\'");
if (index != size - 1) {
conditionParamBuilder.append(" AND ");
}
}
return conditionParamBuilder.toString();
}
private static List<ParamClassInfo> convertParamList(Object obj) {
List<ParamClassInfo> paramClassList = new ArrayList<>();
for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(obj.getClass())) {
if (!"class".equals(pd.getName())) {
if (ReflectionUtils.invokeMethod(pd.getReadMethod(), obj) != null) {
ParamClassInfo paramClassInfo = new ParamClassInfo();
paramClassInfo.setKeyName(pd.getName());
paramClassInfo.setKeyValue(ReflectionUtils.invokeMethod(pd.getReadMethod(), obj));
paramClassInfo.setClassType(pd.getPropertyType().getSimpleName());
paramClassList.add(paramClassInfo);
}
}
}
return paramClassList;
}
public static String camelToUnderline(String line){
if(line==null||"".equals(line)){
return "";
}
line=String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));
StringBuffer sb=new StringBuffer();
Pattern pattern= compile("[A-Z]([a-z\\d]+)?");
Matcher matcher=pattern.matcher(line);
while(matcher.find()){
String word=matcher.group();
sb.append(word.toUpperCase());
sb.append(matcher.end()==line.length()?"":"_");
}
return sb.toString();
}
@Override
public Object plugin(Object o) {
//获取代理权
if (o instanceof Executor) {
//如果是Executor(执行增删改查操作),则拦截下来
return Plugin.wrap(o, this);
} else {
return o;
}
}
/**
* 定义一个内部辅助类,作用是包装 SQL
*/
class MyBoundSqlSqlSource implements SqlSource {
private BoundSql boundSql;
public MyBoundSqlSqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
}
@Override
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 void setProperties(Properties properties) {
//读取mybatis配置文件中属性
}
コード分析:
キャメルケース変換のアンダースコア。データベース テーブルのフィールドを転送するために使用されます。
リフレクションを通じて、SQL 入力パラメーターの空ではないオブジェクトの属性名と対応する値を取り出します。
コンポーネント動的クエリの SQL ステートメント:
簡単なテスト ケースを作成します。
@Autowired
DistrictMapper districtMapper;
@Test
public void test() {
District query = new District();
query.setCode("110000");
query.setName("北京市");
District district = districtMapper.queryOneJcDynamics(query);
System.out.println(district.toString());
District listQuery = new District();
listQuery.setParentCode("110100");
List<District> districts = districtMapper.queryListJcDynamics(listQuery);
System.out.println(districts.toString());
}
効果を見ると、空ではないすべてのフィールドが自動的に認識され、クエリ条件に結合されていることがわかります。
さて、この記事はここまでです。レンガを投げて翡翠を引き寄せ、ステップバイステップのカプセル化のアイデアを理解することが最も重要です。娯楽用の小さなおもちゃを作りに行きましょう。