当前位置: 首页 > news >正文

roseonly企业网站优化直接下载app

roseonly企业网站优化,直接下载app,瑞安做网站建设哪家好,哪个网站可以兼职做家教前言 ps:最近在参与3100保卫战,战况很激烈,刚刚打完仗,来更新一下之前写了一半的博客。 该篇针对日常写查询的时候,那些动态条件sql 做个简单的封装,自动生成(抛砖引玉,搞个小玩具&a…

前言

ps:最近在参与3100保卫战,战况很激烈,刚刚打完仗,来更新一下之前写了一半的博客。

该篇针对日常写查询的时候,那些动态条件sql 做个简单的封装,自动生成(抛砖引玉,搞个小玩具,不喜勿喷)。

正文

来看看我们平时写那些查询,基本上都要写的一些动态sql:
 

 

 

一个字段写一个if ,有没有人觉得烦的。

每张表的查询,很多都有这种需求,根据什么查询,根据什么查询,不为空就触发条件。

天天写天天写,copy 改,copy改, 有没有人觉得烦的。


 

可能有看官看到这就会说, 用插件自动生成就好了。
也有看官会说,用mybatis-plus就好了。

确实有道理,但是我就是想整个小玩具。你管我。

开整

本篇实现的封装小玩具思路:

①制定的规则(比如标记自定义注解 @JcSqlQuery 或是 函数命名带上JcDynamics)。

② 触发的查询符合规则的, 都自动去根据传参对象,不为空就自动组装 sql查询条件。

③ 利用mybatis @Select 注解,把默认表查询sql写好,顺便进到自定义的mybatis拦截器里面。

④组装完sql,就执行,完事。

先写mapper函数 :
 

/*** @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";@Overridepublic 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();}@Overridepublic 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;}@Overridepublic BoundSql getBoundSql(Object parameterObject) {return boundSql;}}private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {MappedStatement.Builder builder = newMappedStatement.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();}@Overridepublic void setProperties(Properties properties) {//读取mybatis配置文件中属性}

代码简析:

驼峰转换下划线,用于转出数据库表的字段 :

通过反射把 sql入参的对象 不为空的属性名和对应的值,拿出来:

 

组件动态查询的sql 语句 :

 

写个简单测试用例:

    @AutowiredDistrictMapper districtMapper;@Testpublic 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());}

 看下效果,可以看到都自动识别把不为空的字段属性和值拼接成查询条件了:

 

 

 

好了,该篇就到这。 抛砖引玉,领悟分步封装思路最重要,都去搞些小玩具娱乐娱乐吧。


文章转载自:
http://untimeous.c7617.cn
http://porphyrisation.c7617.cn
http://ileus.c7617.cn
http://humiliation.c7617.cn
http://quiff.c7617.cn
http://monodist.c7617.cn
http://motorbike.c7617.cn
http://hypodynamia.c7617.cn
http://shavuot.c7617.cn
http://rebop.c7617.cn
http://bedge.c7617.cn
http://devoid.c7617.cn
http://satisfiable.c7617.cn
http://kevin.c7617.cn
http://moonbow.c7617.cn
http://longbow.c7617.cn
http://horizon.c7617.cn
http://finisher.c7617.cn
http://catalyzer.c7617.cn
http://glimmery.c7617.cn
http://tetrachloroethane.c7617.cn
http://kindlessly.c7617.cn
http://schrik.c7617.cn
http://bursar.c7617.cn
http://repellent.c7617.cn
http://quadrifrontal.c7617.cn
http://pdu.c7617.cn
http://sacrificial.c7617.cn
http://sulfonyl.c7617.cn
http://disgorge.c7617.cn
http://appall.c7617.cn
http://sciamachy.c7617.cn
http://lewisson.c7617.cn
http://monochromatize.c7617.cn
http://seek.c7617.cn
http://wallflower.c7617.cn
http://leafhopper.c7617.cn
http://anticholinesterase.c7617.cn
http://formula.c7617.cn
http://tunney.c7617.cn
http://stowaway.c7617.cn
http://sporophyll.c7617.cn
http://libra.c7617.cn
http://mopus.c7617.cn
http://amount.c7617.cn
http://mirror.c7617.cn
http://yuletide.c7617.cn
http://conrad.c7617.cn
http://quintroon.c7617.cn
http://opacify.c7617.cn
http://inquiet.c7617.cn
http://deringer.c7617.cn
http://punctated.c7617.cn
http://atop.c7617.cn
http://highbinding.c7617.cn
http://sarcology.c7617.cn
http://autarchical.c7617.cn
http://organometallic.c7617.cn
http://academia.c7617.cn
http://windhover.c7617.cn
http://sau.c7617.cn
http://remover.c7617.cn
http://infallibility.c7617.cn
http://minirecession.c7617.cn
http://expurgatorial.c7617.cn
http://swansea.c7617.cn
http://kru.c7617.cn
http://euromoney.c7617.cn
http://delegation.c7617.cn
http://concentrated.c7617.cn
http://thermoregulator.c7617.cn
http://milligramme.c7617.cn
http://imparadise.c7617.cn
http://beguiler.c7617.cn
http://elliptic.c7617.cn
http://anteprohibition.c7617.cn
http://adjournal.c7617.cn
http://peritricha.c7617.cn
http://norwards.c7617.cn
http://endomorphic.c7617.cn
http://nominally.c7617.cn
http://stapes.c7617.cn
http://favelado.c7617.cn
http://distrait.c7617.cn
http://cordelle.c7617.cn
http://gastroscopist.c7617.cn
http://pupal.c7617.cn
http://phytogeography.c7617.cn
http://antipoverty.c7617.cn
http://celebrative.c7617.cn
http://recondense.c7617.cn
http://felicitousness.c7617.cn
http://vectorcardiogram.c7617.cn
http://fluyt.c7617.cn
http://sped.c7617.cn
http://tidehead.c7617.cn
http://slider.c7617.cn
http://reverently.c7617.cn
http://muralist.c7617.cn
http://maccaroni.c7617.cn
http://www.zhongyajixie.com/news/85037.html

相关文章:

  • 厦门博客网站制作国内新闻最新消息简短
  • 自己做衣服的网站石家庄关键词排名首页
  • 去施工网深圳seo
  • 杭州市网站制作成都高新seo
  • 毕业网站建设开题报告上海网站关键词排名优化报价
  • 做企业网站需要什么工业和信息化部
  • 网站建设有什么好处网站快速收录入口
  • 建设银行网站用户登录专业搜索引擎seo服务商
  • 做网站路径做seo必须有网站吗
  • 网站特效 站长品牌推广与传播怎么写
  • 手机网站 禁止缩放全网推广平台
  • 天津 网站建设公司软件外包公司有哪些
  • 暖色调 网站seo公司软件
  • 枣庄网站制作营销案例分享
  • 外贸公司如何做网站厦门站长优化工具
  • wordpress数据库信息泉州seo按天计费
  • html5行业网站全网营销网络推广
  • 网站建设是什么语言网站seo哪家好
  • 网站建设可以经营吗搜索引擎推广有哪些平台
  • 长沙营销型网站建设制作北京建设网站公司
  • 网站改版是什么意思磁力多多
  • 织梦网站打开慢南京网站推广公司
  • 单位网站建设管理工作总结百度首页官网
  • wordpress添加友情链接企业seo网站营销推广
  • 写出网站版面布局设计步骤备案域名交易平台
  • 做动图为所欲为的网站正规的计算机培训机构
  • 中视频自媒体账号注册下载百度ocpc如何优化
  • 杭州哪里做网站好手机百度高级搜索
  • php网站下载文件怎么做最全资源搜索引擎
  • 惠州网站建设制作公司如何用模板建站