瀏覽代碼

优化查询sql生成功能

liusz 1 周之前
父節點
當前提交
0ccf6db283

+ 24 - 9
py-base/src/main/java/com/poyee/base/mapper/provider/BaseProvider.java

@@ -1,15 +1,13 @@
 package com.poyee.base.mapper.provider;
 
+import com.baomidou.mybatisplus.annotation.TableName;
 import com.poyee.base.dto.BaseDto;
 import com.poyee.base.dto.BaseReq;
 import com.poyee.base.mapper.provider.domain.LeftJoinInfo;
 import com.poyee.base.mapper.provider.domain.MPage;
 import com.poyee.base.mapper.provider.domain.TableInfo;
 import com.poyee.base.mapper.provider.domain.WhereInfo;
-import com.poyee.base.mapper.provider.util.InsertUtil;
-import com.poyee.base.mapper.provider.util.SelectUtil;
-import com.poyee.base.mapper.provider.util.SqlUtil;
-import com.poyee.base.mapper.provider.util.UpdateUtil;
+import com.poyee.base.mapper.provider.util.*;
 import com.poyee.common.exception.ServiceException;
 import com.poyee.enums.DbMethodEnums;
 import lombok.extern.slf4j.Slf4j;
@@ -39,6 +37,10 @@ public abstract class BaseProvider {
     public Object update;
     // 记录 SELECT
     public Object select;
+    // 请求对象
+    public Object req;
+    // 返回对象
+    public Object res;
     // 主表信息
     public TableInfo superTable;
     //分页查询
@@ -48,11 +50,13 @@ public abstract class BaseProvider {
     //分页查询
     public String pageCountSql;
     // 记录 INSERT key-value(线程安全)
-    public final Map<String, Object> insertMap = new HashMap<>();
+    public final Map<String, Object> insertMap = new ConcurrentHashMap<>();
     // 记录 UPDATE key-value(线程安全)
-    public final Map<String, Object> updateMap = new HashMap<>();
+    public final Map<String, Object> updateMap = new ConcurrentHashMap<>();
     // 存储表信息的映射(线程安全)
-    public final Map<String, TableInfo> tableInfos = new ConcurrentHashMap<>();
+    public final ConcurrentHashMap<String, TableInfo> tableInfos = new ConcurrentHashMap<String, TableInfo>();
+    // 存储类别名
+    public final Map<Class<?>, String> classAlias = new HashMap<>();
     // 记录 WHERE 条件(线程安全)
     public final List<WhereInfo> whereInfos = new CopyOnWriteArrayList<>();
     // 记录 SELECT 列(线程安全)
@@ -60,7 +64,8 @@ public abstract class BaseProvider {
     // 记录 LEFT JOIN 信息(线程安全)
     public final List<LeftJoinInfo> leftJoinInfos = new CopyOnWriteArrayList<>();
     // 记录 ORDER BY 信息(线程安全)
-    public final Map<Integer,String> orderByMap = new HashMap<>();
+    public final Map<Integer,String> orderByMap = new ConcurrentHashMap<>();
+
 
     /**
      * @param req
@@ -90,6 +95,8 @@ public abstract class BaseProvider {
             dbMethod = DbMethodEnums.SELECT_BY_ID;
             // 组装 SELECT 语句
             SelectUtil.init(this).checkSelectBean(object).initSelect(select);
+            // 构建 where
+            WhereUtil.init(this).buildWhere();
             // 生成最终的 SQL 字符串
             return SqlUtil.init(this).buildOne().toSql();
         }
@@ -106,6 +113,8 @@ public abstract class BaseProvider {
             dbMethod = DbMethodEnums.SELECT;
             // 组装 SELECT 语句
             SelectUtil.init(this).checkSelectBean(object).initSelect(select);
+            // 构建 where
+            WhereUtil.init(this).buildWhere();
             // 生成最终的 SQL 字符串
             return SqlUtil.init(this).buildOne().toSql();
         }
@@ -123,6 +132,8 @@ public abstract class BaseProvider {
             dbMethod = DbMethodEnums.SELECT;
             // 组装 SELECT 语句
             SelectUtil.init(this).checkSelectBean(object).initSelect(select);
+            // 构建 where
+            WhereUtil.init(this).buildWhere();
             // 生成最终的 SQL 字符串
             return SqlUtil.init(this).buildSum().toSql();
         }
@@ -169,8 +180,10 @@ public abstract class BaseProvider {
         if (Objects.nonNull(object)) {
             dbMethod = DbMethodEnums.SELECT;
             isPage = true;
-            // 组装 SELECT 语句
+            // 构建 SELECT
             SelectUtil.init(this).checkSelectBean(object).initSelect(select);
+            // 构建 where
+            WhereUtil.init(this).buildWhere();
             // 生成最终的 SQL 字符串
             return SqlUtil.init(this).buildPage().toSql();
         }
@@ -190,6 +203,8 @@ public abstract class BaseProvider {
             dbMethod = DbMethodEnums.SELECT;
             // 组装 SELECT 语句
             SelectUtil.init(this).checkSelectBean(object).initSelect(select);
+            // 构建 where
+            WhereUtil.init(this).buildWhere();
             // 生成最终的 SQL 字符串
             return SqlUtil.init(this).toSql();
         }

+ 1 - 1
py-base/src/main/java/com/poyee/base/mapper/provider/util/InsertUtil.java

@@ -143,7 +143,7 @@ public class InsertUtil {
 
         // 初始化表信息
         TableInfoUtil.init(parent).initTableInfo(aClass);
-        parent.superTable = parent.tableInfos.get(aClass.getName());
+        parent.superTable = parent.tableInfos.get(parent.classAlias.get(aClass));
 
         parent.insert = object;
         return this;

+ 10 - 5
py-base/src/main/java/com/poyee/base/mapper/provider/util/JoinUtil.java

@@ -1,5 +1,6 @@
 package com.poyee.base.mapper.provider.util;
 
+import com.alibaba.excel.util.StringUtils;
 import com.poyee.annotation.db.LeftJoin;
 import com.poyee.base.mapper.provider.BaseProvider;
 import com.poyee.base.mapper.provider.domain.LeftJoinInfo;
@@ -40,13 +41,15 @@ public class JoinUtil {
 
             // 获取注解中指定的连接表类
             Class<?> table = leftJoin.table();
+            String tableName = parent.classAlias.get(table);
             // 如果父对象的表信息映射中不包含此表,初始化该表的信息
-            if (!parent.tableInfos.containsKey(table.getName())) {
+            if (StringUtils.isBlank(tableName ) || !parent.tableInfos.containsKey(tableName)) {
                 TableInfoUtil.init(parent).initTableInfo(table);
+                tableName = parent.classAlias.get(table);
             }
             // 设置左连接信息中的表信息和别名
-            leftJoinInfo.setTableInfo(parent.tableInfos.get(table.getName()));
-            leftJoinInfo.setAlias(parent.tableInfos.get(table.getName()).getAlias());
+            leftJoinInfo.setTableInfo(parent.tableInfos.get(tableName));
+            leftJoinInfo.setAlias(parent.tableInfos.get(tableName).getAlias());
             //判断 左连接 表中是否已存在 leftJoinInfos
             if (CollectionUtils.isNotEmpty(leftJoinInfos)) {
                 boolean b = leftJoinInfos.stream()
@@ -57,12 +60,14 @@ public class JoinUtil {
             }
             // 确定左表,如果注解中未指定则使用传入的实体类
             Class<?> leftTable = leftJoin.leftTable() != void.class ? leftJoin.leftTable() : aClass;
+            String leftTableName = parent.classAlias.get(leftTable);
             // 如果父对象的表信息映射中不包含左表,初始化左表的信息
-            if (!parent.tableInfos.containsKey(leftTable.getName())) {
+            if (StringUtils.isBlank(leftTableName ) || !parent.tableInfos.containsKey(leftTableName)) {
                 TableInfoUtil.init(parent).initTableInfo(leftTable);
+                leftTableName = parent.classAlias.get(leftTable);
             }
             // 设置左连接信息中的左表信息
-            leftJoinInfo.setLeftTableInfo(parent.tableInfos.get(leftTable.getName()));
+            leftJoinInfo.setLeftTableInfo(parent.tableInfos.get(leftTableName));
 
             // 设置左连接信息中的字段名和左表字段名
             leftJoinInfo.setFieldName(leftJoin.fieldName());

+ 103 - 40
py-base/src/main/java/com/poyee/base/mapper/provider/util/SelectUtil.java

@@ -2,6 +2,7 @@ package com.poyee.base.mapper.provider.util;
 
 import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
 import com.poyee.annotation.I18n;
 import com.poyee.annotation.db.*;
 import com.poyee.base.mapper.provider.BaseProvider;
@@ -61,6 +62,8 @@ public class SelectUtil {
         if (Objects.isNull(select)) {
             throw new ServiceException("无法定位返回值!");
         }
+        parent.req = param;
+        parent.res = select;
         if(Objects.equals(parent.dbMethod , SELECT_BY_ID)){
             //组装 select by id
             return this.checkSelectOneBean(param, select);
@@ -69,7 +72,7 @@ public class SelectUtil {
         Class<?> aClass = param.getClass();
         // 初始化表信息
         TableInfoUtil.init(parent).initTableInfo(aClass);
-        parent.superTable = parent.tableInfos.get(aClass.getName());
+        parent.superTable = parent.tableInfos.get(parent.classAlias.get(aClass));
         // 获取超类的所有字段处理分页信息
         if(parent.isPage) {
             long page = 0;
@@ -89,36 +92,8 @@ public class SelectUtil {
             }
             //设置 分页信息
             parent.mPage = new MPage(page, size);
-            try {
-                //处理排序字段
-                Field sidxField = superclass.getDeclaredField("sidx");
-                sidxField.setAccessible(true);
-                Object sidxObj = sidxField.get(param);
-                if(Objects.nonNull(sidxObj) && StringUtils.isNotBlank(String.valueOf(sidxObj))){
-                    parent.isFrontSort = true;
-                    Field sortField = superclass.getDeclaredField("sord");
-                    sortField.setAccessible(true);
-                    String sort = "asc";
-                    if(Objects.nonNull(sortField.get(param))){
-                        sort = sortField.get(param).toString();
-                    }
-                    String alias = parent.superTable.getAlias();
-                    parent.orderByMap.put(Objects.equals(sort,"desc") ? -1 : 0 ,alias +"."+ String.valueOf(sidxObj));
-                }
-            }catch (NoSuchFieldException | IllegalAccessException e) {
-                throw new RuntimeException(e);
-            }
         }
 
-        //设置 排序信息
-        Field[] declaredFields = aClass.getDeclaredFields();
-        for (Field declaredField : declaredFields) {
-            declaredField.setAccessible(true);
-            // 构建 WHERE 条件
-            WhereUtil.init(parent).build(param, aClass, parent.whereInfos, declaredField);
-            // 构建 LEFT JOIN 信息
-            JoinUtil.init(parent).initLeftJoin(aClass, parent.leftJoinInfos, declaredField);
-        }
         parent.select = select;
         return this;
     }
@@ -138,7 +113,7 @@ public class SelectUtil {
         }
         // 初始化表信息
         TableInfoUtil.init(parent).initTableInfo(aClass);
-        parent.superTable = parent.tableInfos.get(aClass.getName());
+        parent.superTable = parent.tableInfos.get(parent.classAlias.get(aClass));
         parent.select = select;
         //获取 主键
         String column = "id";
@@ -148,7 +123,7 @@ public class SelectUtil {
             if(declaredField.isAnnotationPresent(TableId.class)){
                 TableId tableId = declaredField.getAnnotation(TableId.class);
                 column = tableId.value();
-            }else{
+            } else {
                 // 构建 LEFT JOIN 信息
                 JoinUtil.init(parent).initLeftJoin(aClass, parent.leftJoinInfos, declaredField);
             }
@@ -191,13 +166,83 @@ public class SelectUtil {
                 if (!field.isAnnotationPresent(Select.class)
                         && (field.isAnnotationPresent(TableField.class) || field.isAnnotationPresent(TableId.class))) {
                     // 检查字段是否包含TableField注解
-                    processTableFieldAnnotation(field);
+                    processTableFieldAnnotation(clazz, field);
                 } else if (field.isAnnotationPresent(Select.class)) {
                     processSelectAnnotation(field);
                 }
             }
         } catch (Exception e) {
             log.error("初始化选择对象时发生异常", e);
+        } finally {
+            //如果是分页 则处理 order by
+            if (parent.isPage) {
+                Object req = parent.req;
+                Class<?> superclass = req.getClass().getSuperclass();
+                Object res = parent.res;
+                //处理order by
+                //todo 排序需要在最后组装sql 的时候进行解析, 此时所有的实体类均已经做好解析映射
+                try {
+                    //处理排序字段
+                    Field sidxField = superclass.getDeclaredField("sidx");
+                    sidxField.setAccessible(true);
+                    Object sidxObj = sidxField.get(req);
+                    //如果是 请求端 传排序字段 则 需要 解析 请求参数映射的表结构
+                    if(Objects.nonNull(sidxObj) && StringUtils.isNotBlank(String.valueOf(sidxObj))){
+                        parent.isFrontSort = true;
+                        Field sortField = superclass.getDeclaredField("sord");
+                        sortField.setAccessible(true);
+                        String sort = "asc";
+                        if(Objects.nonNull(sortField.get(req))){
+                            sort = sortField.get(req).toString();
+                        }
+                        //获取返回类的字段的 表的别名
+                        Class<?> resClass = res.getClass();
+                        Field declaredField = resClass.getDeclaredField(String.valueOf(sidxObj));
+                        String alias = parent.superTable.getAlias();
+                        if(Objects.nonNull(declaredField)){
+                            //是否存在 @Select 注解
+                            if(declaredField.isAnnotationPresent(Select.class)){
+                                Select selectAnn = declaredField.getAnnotation(Select.class);
+                                //如果存在则获取 该注解的table 对应的别名
+                                TableInfo tableInfo = parent.tableInfos.get(parent.classAlias.get(selectAnn.table()));
+                                if(Objects.nonNull(tableInfo)){
+                                    alias = tableInfo.getAlias();
+                                }
+                            }else if(declaredField.isAnnotationPresent(LeftJoin.class)){//存在 leftjoin注解
+                                LeftJoin leftJoin = declaredField.getAnnotation(LeftJoin.class);
+                                TableInfo tableInfo = parent.tableInfos.get(parent.classAlias.get(leftJoin.table()));
+                                if(Objects.nonNull(tableInfo)){
+                                    alias = tableInfo.getAlias();
+                                }
+                            }else if(declaredField.isAnnotationPresent(RightJoin.class)){//RightJoin
+                                RightJoin rightJoin = declaredField.getAnnotation(RightJoin.class);
+                                TableInfo tableInfo = parent.tableInfos.get(parent.classAlias.get(rightJoin.table()));
+                                if(Objects.nonNull(tableInfo)){
+                                    alias = tableInfo.getAlias();
+                                }
+                            }else if(declaredField.isAnnotationPresent(Join.class)){//join
+                                Join join = declaredField.getAnnotation(Join.class);
+                                TableInfo tableInfo = parent.tableInfos.get(parent.classAlias.get(join.table()));
+                                if(Objects.nonNull(tableInfo)){
+                                    alias = tableInfo.getAlias();
+                                }
+                            }else if(declaredField.isAnnotationPresent(TableField.class)){// TableField
+                                //如果存在则获取当前 class 的taleName 注解
+                                TableName tableName = resClass.getAnnotation(TableName.class);
+                                if(Objects.nonNull(tableName) && StringUtils.isNotBlank(tableName.value())){
+                                    TableInfo tableInfo = parent.tableInfos.get(tableName.value());
+                                    if(Objects.nonNull(tableInfo)){
+                                        alias = tableInfo.getAlias();
+                                    }
+                                }
+                            }
+                        }
+                        parent.orderByMap.put(Objects.equals(sort,"desc") ? -1 : 0 ,alias +"."+ String.valueOf(sidxObj));
+                    }
+                }catch (NoSuchFieldException | IllegalAccessException e) {
+                    throw new RuntimeException(e);
+                }
+            }
         }
     }
 
@@ -206,10 +251,22 @@ public class SelectUtil {
      *
      * @param field 字段对象
      */
-    private void processTableFieldAnnotation(Field field) {
+    private void processTableFieldAnnotation(Class<?> clazz ,Field field) {
         try {
+
+            TableInfo superTable = null;
+            //获取表信息
+            String tableName = parent.classAlias.get(clazz);
+            if(StringUtils.isBlank(tableName)){
+                superTable = TableInfoUtil.init(parent).initTableInfo(clazz);
+            } else {
+                superTable = parent.tableInfos.get(tableName);
+            }
+//            if(Objects.isNull(superTable)){
+//                superTable = parent.superTable;
+//            }
+
             boolean isDistinct = field.isAnnotationPresent(Distinct.class);
-            TableInfo superTable = parent.superTable;
             TableId tableId = field.getAnnotation(TableId.class);
             if (Objects.nonNull(tableId)) {
                 String selectSql = "";
@@ -330,20 +387,26 @@ public class SelectUtil {
      */
     private void processSelectAnnotation(Field field) {
         try {
+
+
             Select selectAnnotation = field.getAnnotation(Select.class);
             boolean isDistinct = field.isAnnotationPresent(Distinct.class) || selectAnnotation.distinct() ;
             if (Objects.nonNull(selectAnnotation.table())) {
-                String tableName = selectAnnotation.table()
-                                                   .getName();
-                TableInfo tableInfo = parent.tableInfos.get(tableName);
+//                String tableName = selectAnnotation.table().getName();
+                String tableNames = parent.classAlias.get(selectAnnotation.table());
+                if(StringUtils.isBlank(tableNames) ){
+                    TableInfoUtil.init(parent).initTableInfo(selectAnnotation.table());
+                    tableNames = parent.classAlias.get(selectAnnotation.table());
+                }
+                TableInfo tableInfo = parent.tableInfos.get(tableNames);
                 if(Objects.isNull(tableInfo)){
                     //如果未查到 但有别名则使用别名进行匹配
                     String alias = selectAnnotation.alias();
                     if(StringUtils.isNotBlank(alias)){
                         tableInfo = TableInfoUtil.init(parent).initTableInfoByAlias(selectAnnotation.table(), alias);
                     } else {
-                        TableInfoUtil.init(parent).initTableInfo(selectAnnotation.table());
-                        tableInfo = parent.tableInfos.get(tableName);
+                        tableInfo = TableInfoUtil.init(parent).initTableInfo(selectAnnotation.table());
+//                        tableInfo = parent.tableInfos.get(tableNames);
                     }
                 }
                 if (Objects.nonNull(tableInfo)) {
@@ -357,7 +420,7 @@ public class SelectUtil {
                     checkSelectSql(selectSql, field, tableInfo, selectAnnotation.fieldName());
 //                    parent.selectColumns.add(selectSql);
                 } else {
-                    log.warn("未找到表名 {} 对应的 TableInfo 对象", tableName);
+                    log.warn("未找到表名 {} 对应的 TableInfo 对象", tableNames);
                 }
             }
         } catch (Exception e) {

+ 25 - 9
py-base/src/main/java/com/poyee/base/mapper/provider/util/TableInfoUtil.java

@@ -41,8 +41,14 @@ public class TableInfoUtil {
         TableName tableName = aClass.getAnnotation(TableName.class);
         String firstTableName = tableName.value();
         //判断是否已经存在表
-        if(parent.tableInfos.containsKey(aClass.getName())){
+        /*if(parent.tableInfos.containsKey(aClass.getName())){
             return parent.tableInfos.get(aClass.getName());
+        }*/
+        if(parent.tableInfos.containsKey(firstTableName)){
+            if(!parent.classAlias.containsKey(aClass)){
+                parent.classAlias.put(aClass, firstTableName);
+            }
+            return parent.tableInfos.get(firstTableName);
         }
         // 根据parent.tableCount的值生成表的别名
         String thisAlisa = "_" + parent.tableCount;
@@ -55,10 +61,13 @@ public class TableInfoUtil {
             primaryKey = aClass.getAnnotation(TableId.class).value();
         }
         // 创建TableInfo对象,并将其存入parent.tableInfos中
-        parent.tableInfos.put(aClass.getName(), new TableInfo(aClass.getName(), aClass, firstTableName, "t" + thisAlisa, parent.tableCount, primaryKey));
+//        parent.tableInfos.put(aClass.getName(), new TableInfo(aClass.getName(), aClass, firstTableName, "t" + thisAlisa, parent.tableCount, primaryKey));
+        parent.tableInfos.put(firstTableName, new TableInfo(aClass.getName(), aClass, firstTableName, "t" + thisAlisa, parent.tableCount, primaryKey));
+        parent.classAlias.put(aClass, firstTableName);
         // 增加parent.tableCount的值,为下一个表生成别名做准备
         parent.tableCount++;
-        return parent.tableInfos.get(aClass.getName());
+        return parent.tableInfos.get(firstTableName);
+//        return parent.tableInfos.get(aClass.getName());
     }
 
     /**
@@ -71,13 +80,19 @@ public class TableInfoUtil {
         if (!aClass.isAnnotationPresent(TableName.class)) {
             throw new ServiceException(aClass.getName() + "未设置表名");
         }
-        //判断是否已经存在表
-        if(parent.tableInfos.containsKey(aClass.getName())){
-            return parent.tableInfos.get(aClass.getName());
-        }
         // 获取@TableName注解的值,作为表名
         TableName tableName = aClass.getAnnotation(TableName.class);
         String firstTableName = tableName.value();
+        //判断是否已经存在表
+        /*if(parent.tableInfos.containsKey(aClass.getName())){
+            return parent.tableInfos.get(aClass.getName());
+        }*/
+        if(parent.tableInfos.containsKey(firstTableName)){
+            if(!parent.classAlias.containsKey(aClass)){
+                parent.classAlias.put(aClass, firstTableName);
+            }
+            return parent.tableInfos.get(firstTableName);
+        }
         //根据别名获取表信息
         TableInfo tableInfo = parent.tableInfos.values().stream()
                 .filter(tableInfo1 -> tableInfo1.getAlias().equals(alias))
@@ -97,10 +112,11 @@ public class TableInfoUtil {
             primaryKey = aClass.getAnnotation(TableId.class).value();
         }
         // 创建TableInfo对象,并将其存入parent.tableInfos中
-        parent.tableInfos.put(aClass.getName(), new TableInfo(aClass.getName(), aClass, firstTableName, alias + thisAlisa, parent.tableCount, primaryKey));
+        parent.tableInfos.put(firstTableName, new TableInfo(aClass.getName(), aClass, firstTableName, alias + thisAlisa, parent.tableCount, primaryKey));
+        parent.classAlias.put(aClass, firstTableName);
         // 增加parent.tableCount的值,为下一个表生成别名做准备
         parent.tableCount++;
-        return parent.tableInfos.get(aClass.getName());
+        return parent.tableInfos.get(firstTableName);
     }
 
 }

+ 4 - 2
py-base/src/main/java/com/poyee/base/mapper/provider/util/UpdateUtil.java

@@ -147,11 +147,13 @@ public class UpdateUtil {
                             || (!(value instanceof String) && Objects.nonNull(value))
                             || FieldOperator.checkEmptyValue(where)) {
                         Class<?> table = where.table();
+                        String tableName = parent.classAlias.get(table);
                         // 确保表信息已初始化
-                        if (!parent.tableInfos.containsKey(table.getName())) {
+                        if (StringUtils.isBlank(tableName ) || !parent.tableInfos.containsKey(tableName)) {
                             TableInfoUtil.init(parent).initTableInfo(table);
+                            tableName = parent.classAlias.get(table);
                         }
-                        WhereInfo whereInfo = new WhereInfo(parent.tableInfos.get(table.getName()));
+                        WhereInfo whereInfo = new WhereInfo(parent.tableInfos.get(tableName));
                         whereInfo.setColumn(where.field());
                         whereInfo.setValue(value);
                         whereInfo.setOperator(where.operator());

+ 26 - 4
py-base/src/main/java/com/poyee/base/mapper/provider/util/WhereUtil.java

@@ -29,6 +29,24 @@ public class WhereUtil {
     }
     private BaseProvider parent;
 
+    /**
+     *  构建 WHERE 信息
+     */
+    public void buildWhere() {
+        //处理 where
+        Object req = parent.req;
+        Class<?> aclass = req.getClass();
+        //处理 where
+        //设置到请求参数之后 设置 排序信息
+        Field[] declaredFields = aclass.getDeclaredFields();
+        for (Field declaredField : declaredFields) {
+            declaredField.setAccessible(true);
+            // 构建 WHERE 条件
+            build(req, aclass, parent.whereInfos, declaredField);
+            // 构建 LEFT JOIN 信息
+            JoinUtil.init(parent).initLeftJoin(aclass, parent.leftJoinInfos, declaredField);
+        }
+    }
     /**
      * 处理 WHERE 条件。
      *
@@ -49,10 +67,12 @@ public class WhereUtil {
                         || FieldOperator.checkEmptyValue(where)) {
                     Class<?> table = where.table();
                     // 确保表信息已初始化
-                    if (!parent.tableInfos.containsKey(table.getName())) {
+                    String tableName = parent.classAlias.get(table);
+                    if (StringUtils.isBlank(tableName ) || !parent.tableInfos.containsKey(tableName)) {
                         TableInfoUtil.init(parent).initTableInfo(table);
+                        tableName = parent.classAlias.get(table);
                     }
-                    WhereInfo whereInfo = new WhereInfo(parent.tableInfos.get(table.getName()));
+                    WhereInfo whereInfo = new WhereInfo(parent.tableInfos.get(tableName));
                     // 处理自定义查询条件
                     if (checkCustomConditions(where, whereInfo,value)){
                         whereInfos.add(whereInfo);
@@ -95,7 +115,7 @@ public class WhereUtil {
                         Object value = field.get(object);
                         // 如果字段值非空,则创建 WHERE 信息并添加到列表中
                         if ((value instanceof String && StringUtils.isNotBlank(String.valueOf(value))) || (!(value instanceof String) && Objects.nonNull(value))) {
-                            WhereInfo whereInfo = new WhereInfo(parent.tableInfos.get(aClass.getName()));
+                            WhereInfo whereInfo = new WhereInfo(parent.tableInfos.get(parent.classAlias.get(aClass)));
                             whereInfo.setColumn(tableField.value());
                             whereInfo.setValue(valueCase(value,field));
                             whereInfo.setOperator(FieldOperator.EQ);
@@ -112,7 +132,7 @@ public class WhereUtil {
                     Object value = field.get(object);
                     // 如果字段值非空,则创建 WHERE 信息并添加到列表中
                     if ((value instanceof String && StringUtils.isNotBlank(String.valueOf(value))) || (!(value instanceof String) && Objects.nonNull(value))) {
-                        WhereInfo whereInfo = new WhereInfo(parent.tableInfos.get(aClass.getName()));
+                        WhereInfo whereInfo = new WhereInfo(parent.tableInfos.get(parent.classAlias.get(aClass)));
                         whereInfo.setColumn(tableId.value());
                         whereInfo.setValue(valueCase(value,field));
                         whereInfo.setOperator(FieldOperator.EQ);
@@ -181,4 +201,6 @@ public class WhereUtil {
         return value;
     }
 
+
+
 }

+ 78 - 0
py-domain/src/main/java/com/poyee/req/goods/EcologyGoodsBuyReq.java

@@ -0,0 +1,78 @@
+package com.poyee.req.goods;
+
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableName;
+import com.poyee.annotation.db.LeftJoin;
+import com.poyee.annotation.db.OrderBy;
+import com.poyee.annotation.db.Where;
+import com.poyee.base.dto.BaseReq;
+import com.poyee.enums.FieldOperator;
+import com.poyee.enums.OrderBySortEnums;
+import com.poyee.enums.ProductBusinessTypeEnums;
+import com.poyee.req.EcologySkuReq;
+import com.poyee.req.EcologySpuReq;
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Data;
+
+@ApiModel(description = "商品查询对象")
+@Data
+@TableName("ecology_mer_customize")
+public class EcologyGoodsBuyReq extends BaseReq {
+
+    @ApiModelProperty(value = "商户id", example = "1",hidden = true)
+    @TableField(value = "merchant_id")
+    private Integer merchantId;
+
+    /**
+     * 类别:求购(buy)、热卖(hot)、专供(supply)
+     * @see ProductBusinessTypeEnums
+     */
+    @ApiModelProperty(value = "类别", example = "hot", hidden = true)
+    @TableField("category")
+    private String category;
+
+    //推广优先级 数字越大优先级越高
+    @ApiModelProperty(value = "推广优先级 默认为0", example = "0",hidden = true)
+    @TableField(value = "priority")
+    @OrderBy(sortType = OrderBySortEnums.DESC)
+    private Integer priority;
+
+    /**
+     *  SPU状态:000=待提交,100=待审核,200=审核通过,201=审核驳回,300=上架,999=下架
+     *
+     */
+    @ApiModelProperty(value = "SPU状态:000=待提交,100=待审核,200=审核通过,201=审核驳回,300=上架,999=下架", example = "1",hidden = true)
+    @TableField(value = "status",exist = false)
+    @Where(table = EcologySpuReq.class , field = "status" ,operator = FieldOperator.EQ)
+    @LeftJoin(table = EcologySpuReq.class , fieldName = "id" , leftFieldName = "spu_id")
+    private Integer spuStatus;
+
+    /**
+     * show_applet
+     */
+    @ApiModelProperty(value = "公私域:0=私域,1=公域", example = "1",hidden = true)
+    @TableField(value = "show_applet",exist = false)
+    @Where(table = EcologySpuReq.class , field = "show_applet" ,operator = FieldOperator.EQ)
+    @LeftJoin(table = EcologySpuReq.class , fieldName = "id" , leftFieldName = "spu_id")
+    private Integer showApplet;
+
+    @ApiModelProperty(value = "业务类型:求购(buy)、热卖(hot)、专供(supply)等", example = "buy",hidden = true)
+    @TableField(exist = false)
+    @Where(table = EcologySkuReq.class , field = "business_type" ,operator = FieldOperator.EQ)
+    @LeftJoin(table = EcologySkuReq.class , fieldName = "id" , leftFieldName = "sku_id")
+    private String skuBusinessType;
+
+    @ApiModelProperty(value = "SKU状态:000=待提交,100=待审核,200=审核通过,201=审核驳回,300=上架,999=下架", example = "1",hidden = true)
+    @TableField(value = "status",exist = false)
+    @Where(table = EcologySkuReq.class , field = "status" ,operator = FieldOperator.EQ)
+    @LeftJoin(table = EcologySkuReq.class , fieldName = "id" , leftFieldName = "sku_id")
+    private Integer skuStatus;
+
+    @ApiModelProperty(value = "skuId", example = "1",hidden = true)
+    @TableField(value = "sku_id",exist = false)
+    @LeftJoin(table = EcologySkuReq.class , fieldName = "id" , leftFieldName = "sku_id")
+    private String skuId;
+
+
+}

+ 2 - 1
py-domain/src/main/java/com/poyee/req/goods/EcologyGoodsPageReq.java

@@ -28,7 +28,8 @@ public class EcologyGoodsPageReq extends BaseReq {
     private Integer merchantId;
 
     @ApiModelProperty(value = "商品名称", example = "noir")
-    @TableField("name")
+    @TableField(value = "name",exist = false)
+    @Where(table = EcologySkuReq.class , field = "name" ,operator = FieldOperator.ILIKE)
     private String name;
 
     /**

+ 7 - 2
py-service/src/main/java/com/poyee/build/ProductBeanBuildFactory.java

@@ -1,6 +1,7 @@
 package com.poyee.build;
 
 import com.poyee.constant.DomainConstants;
+import com.poyee.dto.EcologyMerCustomizeDto;
 import com.poyee.dto.EcologySkuDto;
 import com.poyee.enums.GoodsQueryTypeEnums;
 import com.poyee.enums.ProductBusinessTypeEnums;
@@ -74,7 +75,7 @@ public class ProductBeanBuildFactory {
      * @param bussinessTypeSkuMap
      * @return
      */
-    public static List<EcologyMerCustomizeReq> builderMerCustomizeParam(EcologySpuSyncReq req, SpuInsertDao spuInsertDao, Map<String, EcologySkuDto> bussinessTypeSkuMap) {
+    public static List<EcologyMerCustomizeReq> builderMerCustomizeParam(EcologySpuSyncReq req, SpuInsertDao spuInsertDao, Map<String, EcologySkuDto> bussinessTypeSkuMap, Map<Long, Integer> maxPriorityMap) {
         List<EcologyMerCustomizeReq> list = new ArrayList<>();
         //根据sku 业务类型 和req 的 求购令商家 和 热卖商家集合进行设置不同数据集合
         for (Map.Entry<String, EcologySkuDto> entry : bussinessTypeSkuMap.entrySet()) {
@@ -102,7 +103,11 @@ public class ProductBeanBuildFactory {
                     customizeReq.setSkuName(skuInsertDao.getName());
                     customizeReq.setCategory(businessType);//分类:求购(buy)、热卖(hot)、专供(supply)
                     customizeReq.setRecommendType(businessType);//推广类型: 求购(buy)、热卖(hot)、hot(热销), new(新品), promotion(促销)
-                    customizeReq.setPriority(1);
+                    int priority = 1;
+                    if(Objects.nonNull(maxPriorityMap) && maxPriorityMap.containsKey(merInfo.getId())){
+                        priority = maxPriorityMap.get(merInfo.getId()) + 1;
+                    }
+                    customizeReq.setPriority(priority);
                     customizeReq.setEnabled(1);
                     list.add(customizeReq);
                 }

+ 26 - 4
py-service/src/main/java/com/poyee/service/impl/EcologyGoodsServiceImpl.java

@@ -18,6 +18,7 @@ import com.poyee.mapper.EcologyGoodsMapper;
 import com.poyee.query.CheckMerPermissionQuery;
 import com.poyee.req.EcologyMerCustomizeReq;
 import com.poyee.req.goods.EcologyGoodsBuyPageReq;
+import com.poyee.req.goods.EcologyGoodsBuyReq;
 import com.poyee.req.goods.EcologyGoodsPageReq;
 import com.poyee.service.EcologyGoodsService;
 import lombok.extern.slf4j.Slf4j;
@@ -166,10 +167,31 @@ public class EcologyGoodsServiceImpl extends BaseServiceImpl<EcologyGoodsMapper,
      */
     @Override
     public Result<EcologyGoodsPageDto> buyTop() {
-
-
-
-        return null;
+        //设置商家id
+        EcologyGoodsBuyReq req = new EcologyGoodsBuyReq();
+        checkAndSetMerchantId(req);
+        //组装查询实体类对象
+        req.setCategory("buy");
+//        req.setSpuStatus(300);//显示上架商品
+//        req.setShowApplet(1);//显示公域商品
+//        req.setSkuStatus(300);//显示上架商品
+        req.setSkuBusinessType("buy");//求购
+        EcologyGoodsDetailDto baseDto =  Optional.ofNullable((EcologyGoodsDetailDto) baseMapper.selectOne(req, EcologyGoodsDetailDto.class))
+                                                 .orElseThrow(() -> new ServiceException("商品不存在"));
+        // "tags": "\"recommend\",\"hot\""
+        // 移除前后方括号并去除recommend标签,然后去除前后多余的逗号和空格
+        String tags = baseDto.getTags();
+        if (tags != null && !tags.isEmpty()) {
+            // 移除首尾的方括号,移除双引号并按逗号分割
+            String processedTags = Arrays.stream(tags.replaceAll("^\\[|\\]$", "").split(","))
+                                         .map(tag -> tag.trim().replaceAll("^\"|\"$", "")) // 去除每个标签的首尾空格和双引号
+                                         .filter(tag -> !tag.isEmpty() && !"recommend".equals(tag)) // 过滤空标签和recommend标签
+                                         .collect(Collectors.joining(",")); // 重新用逗号连接
+            baseDto.setTags(processedTags);
+        } else {
+            baseDto.setTags("");
+        }
+        return Result.success(baseDto);
     }
 
 

+ 7 - 3
py-service/src/main/java/com/poyee/service/impl/EcologySpuServiceImpl.java

@@ -98,6 +98,7 @@ public class EcologySpuServiceImpl extends BaseServiceImpl<EcologySpuMapper, Eco
                 }
             }
             //查询商家 关联求购商品的推广优先级【max】
+            Map<Long, Integer> maxPriorityMap = new HashMap<>();
             if (CollectionUtils.isNotEmpty(req.getBuyMers())) {
                 String buyMerIds = req.getBuyMers()
                                       .stream()
@@ -108,11 +109,14 @@ public class EcologySpuServiceImpl extends BaseServiceImpl<EcologySpuMapper, Eco
                                       .collect(Collectors.joining(","));
                 //查询商家 求购产品的最大优先级
                 List<EcologyMerCustomizeDto> maxPriorityList = merCustomizeMapper.getMaxPriority(buyMerIds);
-
+                //转换为 merchantId , maxPriority 的map 集合
+                if(CollectionUtils.isNotEmpty(maxPriorityList)) {
+                    maxPriorityMap = maxPriorityList.stream().collect(Collectors.toMap(EcologyMerCustomizeDto::getMerchantId, EcologyMerCustomizeDto::getPriority));
+                }
+                log.info("查询商家 推广优先级【max】");
             }
             // 新增 商家产品推广关联
-            List<EcologyMerCustomizeReq> merCustomizeReqList =
-                    ProductBeanBuildFactory.builderMerCustomizeParam(req, spuInsertDao, bussinessTypeSkuMap);
+            List<EcologyMerCustomizeReq> merCustomizeReqList = ProductBeanBuildFactory.builderMerCustomizeParam(req, spuInsertDao, bussinessTypeSkuMap,maxPriorityMap);
             if (CollectionUtils.isNotEmpty(merCustomizeReqList)) {
                 //如果有值则进行批量新增
                 //分批次新增 100条 新增一次

+ 3 - 0
py-starter/src/main/resources/db/V1.0.10__ecologu_sku_update.sql

@@ -0,0 +1,3 @@
+CREATE INDEX idx_ecology_sku_name ON ecology_sku USING btree (
+                                                              name pg_catalog.text_ops ASC NULLS LAST
+    );