Kaynağa Gözat

修复@OrderBy搭配@TableId排序字段错误.

https://github.com/baomidou/mybatis-plus/issues/5676
nieqiurong 1 yıl önce
ebeveyn
işleme
0bd287f1db

+ 5 - 4
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/injector/AbstractMethod.java

@@ -15,6 +15,7 @@
  */
 package com.baomidou.mybatisplus.core.injector;
 
+import com.baomidou.mybatisplus.core.metadata.OrderFieldInfo;
 import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
 import com.baomidou.mybatisplus.core.metadata.TableInfo;
 import com.baomidou.mybatisplus.core.toolkit.Assert;
@@ -260,15 +261,15 @@ public abstract class AbstractMethod implements Constants {
 
     protected String sqlOrderBy(TableInfo tableInfo) {
         /* 不存在排序字段,直接返回空 */
-        List<TableFieldInfo> orderByFields = tableInfo.getOrderByFields();
+        List<OrderFieldInfo> orderByFields = tableInfo.getOrderByFields();
         if (CollectionUtils.isEmpty(orderByFields)) {
             return StringPool.EMPTY;
         }
-        orderByFields.sort(Comparator.comparingInt(TableFieldInfo::getOrderBySort));
+        orderByFields.sort(Comparator.comparingInt(OrderFieldInfo::getSort));
         StringBuilder sql = new StringBuilder();
         sql.append(NEWLINE).append(" ORDER BY ");
-        sql.append(orderByFields.stream().map(tfi -> String.format("%s %s", tfi.getColumn(),
-            tfi.getOrderByType())).collect(joining(",")));
+        sql.append(orderByFields.stream().map(orderFieldInfo -> String.format("%s %s", orderFieldInfo.getColumn(),
+            orderFieldInfo.getType())).collect(joining(",")));
         /* 当wrapper中传递了orderBy属性,@orderBy注解失效 */
         return SqlScriptUtils.convertIf(sql.toString(), String.format("%s == null or %s", WRAPPER,
             WRAPPER_EXPRESSION_ORDER), true);

+ 51 - 0
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/metadata/OrderFieldInfo.java

@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2011-2023, baomidou (jobob@qq.com).
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.baomidou.mybatisplus.core.metadata;
+
+import com.baomidou.mybatisplus.core.toolkit.Constants;
+import lombok.Data;
+
+/**
+ * @author nieqiurong
+ * @since 3.5.4
+ */
+@Data
+public class OrderFieldInfo {
+
+    /**
+     * 字段
+     */
+    private String column;
+
+    /**
+     * 排序类型
+     */
+    private String type;
+
+    /**
+     * 排序顺序
+     */
+    private short sort;
+
+
+    public OrderFieldInfo(String column, boolean asc, short orderBySort) {
+        this.column = column;
+        this.type = asc ? Constants.ASC : Constants.DESC;
+        this.sort = orderBySort;
+    }
+
+}

+ 6 - 8
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/metadata/TableFieldInfo.java

@@ -198,7 +198,7 @@ public class TableFieldInfo implements Constants {
         this(globalConfig, tableInfo, field, tableField, reflector, existTableLogic);
         this.isOrderBy = isOrderBy;
         if (isOrderBy) {
-            initOrderBy(globalConfig.getAnnotationHandler().getAnnotation(field, OrderBy.class));
+            initOrderBy(tableInfo, globalConfig.getAnnotationHandler().getAnnotation(field, OrderBy.class));
         }
     }
 
@@ -327,7 +327,7 @@ public class TableFieldInfo implements Constants {
         this(globalConfig, tableInfo, field, reflector, existTableLogic);
         this.isOrderBy = isOrderBy;
         if (isOrderBy) {
-            initOrderBy(globalConfig.getAnnotationHandler().getAnnotation(field, OrderBy.class));
+            initOrderBy(tableInfo, globalConfig.getAnnotationHandler().getAnnotation(field, OrderBy.class));
         }
     }
 
@@ -383,17 +383,15 @@ public class TableFieldInfo implements Constants {
     /**
      * 排序初始化
      *
+     * @param tableInfo 表信息
      * @param orderBy 排序注解
      */
-    private void initOrderBy(OrderBy orderBy) {
+    private void initOrderBy(TableInfo tableInfo, OrderBy orderBy) {
         if (null != orderBy) {
             this.isOrderBy = true;
             this.orderBySort = orderBy.sort();
-            String _orderBy = Constants.DESC;
-            if (orderBy.asc()) {
-                _orderBy = Constants.ASC;
-            }
-            this.orderByType = _orderBy;
+            this.orderByType = orderBy.asc() ? Constants.ASC : Constants.DESC;
+            tableInfo.getOrderByFields().add(new OrderFieldInfo(this.getColumn(), orderBy.asc(), orderBy.sort()));
         } else {
             this.isOrderBy = false;
         }

+ 2 - 5
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/metadata/TableInfo.java

@@ -177,7 +177,7 @@ public class TableInfo implements Constants {
      * 排序列表
      */
     @Setter
-    private List<TableFieldInfo> orderByFields;
+    private List<OrderFieldInfo> orderByFields;
 
     /**
      * @since 3.4.4
@@ -503,9 +503,6 @@ public class TableInfo implements Constants {
             if (i.isWithUpdateFill()) {
                 this.withUpdateFill = true;
             }
-            if (i.isOrderBy()) {
-                this.getOrderByFields().add(i);
-            }
             if (i.isVersion()) {
                 this.withVersion = true;
                 this.versionFieldInfo = i;
@@ -521,7 +518,7 @@ public class TableInfo implements Constants {
         return Collections.unmodifiableList(fieldList);
     }
 
-    public List<TableFieldInfo> getOrderByFields() {
+    public List<OrderFieldInfo> getOrderByFields() {
         if (null == this.orderByFields) {
             this.orderByFields = new LinkedList<>();
         }

+ 4 - 5
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/metadata/TableInfoHelper.java

@@ -328,8 +328,8 @@ public class TableInfoHelper {
             }
 
             boolean isPK = false;
-            boolean isOrderBy = annotationHandler.getAnnotation(field, OrderBy.class) != null;
-
+            OrderBy orderBy = annotationHandler.getAnnotation(field, OrderBy.class);
+            boolean isOrderBy = orderBy != null;
             /* 主键ID 初始化 */
             if (existTableId) {
                 TableId tableId = annotationHandler.getAnnotation(field, TableId.class);
@@ -346,12 +346,11 @@ public class TableInfoHelper {
             }
 
             if (isPK) {
-                if (isOrderBy) {
-                    tableInfo.getOrderByFields().add(new TableFieldInfo(globalConfig, tableInfo, field, reflector, existTableLogic, true));
+                if (orderBy != null) {
+                    tableInfo.getOrderByFields().add(new OrderFieldInfo(tableInfo.getKeyColumn(), orderBy.asc(), orderBy.sort()));
                 }
                 continue;
             }
-
             final TableField tableField = annotationHandler.getAnnotation(field, TableField.class);
 
             /* 有 @TableField 注解的字段初始化 */

+ 29 - 0
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/orderby/OrderByEntity.java

@@ -0,0 +1,29 @@
+package com.baomidou.mybatisplus.test.orderby;
+
+import com.baomidou.mybatisplus.annotation.OrderBy;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+/**
+ * @author nieqiurong
+ */
+@Data
+@TableName(value = "t_order_test")
+public class OrderByEntity {
+
+    @OrderBy(sort = 3)
+    @TableId(value = "oid")
+    private Long id;
+
+    private String name;
+
+    @OrderBy(asc = true, sort = 2)
+    @TableField("nl")
+    private Long age;
+
+    @OrderBy
+    private String tel;
+
+}

+ 9 - 0
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/orderby/OrderByMapper.java

@@ -0,0 +1,9 @@
+package com.baomidou.mybatisplus.test.orderby;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+
+/**
+ * @author nieqiurong
+ */
+public interface OrderByMapper extends BaseMapper<OrderByEntity> {
+}

+ 56 - 0
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/orderby/OrderByMapperTest.java

@@ -0,0 +1,56 @@
+package com.baomidou.mybatisplus.test.orderby;
+
+import com.baomidou.mybatisplus.core.metadata.OrderFieldInfo;
+import com.baomidou.mybatisplus.core.metadata.TableInfo;
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
+import com.baomidou.mybatisplus.core.toolkit.Constants;
+import com.baomidou.mybatisplus.core.toolkit.Wrappers;
+import com.baomidou.mybatisplus.test.BaseDbTest;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * @author nieqiurong
+ */
+public class OrderByMapperTest extends BaseDbTest<OrderByMapper> {
+    @Test
+    void test() {
+        doTest(mapper -> {
+            mapper.selectList(Wrappers.emptyWrapper());
+
+            mapper.selectList(Wrappers.<OrderByEntity>lambdaQuery().select(OrderByEntity::getName));
+        });
+        TableInfo tableInfo = TableInfoHelper.getTableInfo(OrderByEntity.class);
+        for (OrderFieldInfo orderByField : tableInfo.getOrderByFields()) {
+            if ("oid".equals(orderByField.getColumn())) {
+                Assertions.assertEquals(orderByField.getSort(), 3);
+                Assertions.assertEquals(orderByField.getType(), Constants.DESC);
+            } else if ("age".equals(orderByField.getColumn())) {
+                Assertions.assertEquals(orderByField.getSort(), 2);
+                Assertions.assertEquals(orderByField.getType(), Constants.ASC);
+            } else if ("tel".equals(orderByField.getColumn())) {
+                Assertions.assertEquals(orderByField.getSort(), Short.MAX_VALUE);
+                Assertions.assertEquals(orderByField.getType(), Constants.DESC);
+            }
+        }
+    }
+
+    @Override
+    protected String tableDataSql() {
+        return "insert into t_order_test(oid,name,nl,tel) values(1,'demo1',12, '13311111111'),(2,'demo2',13, '13322222222'),(3,'demo3',14, '13333333333');";
+    }
+
+    @Override
+    protected List<String> tableSql() {
+        return Arrays.asList("drop table if exists t_order_test", "CREATE TABLE IF NOT EXISTS t_order_test (" +
+            "oid BIGINT NOT NULL," +
+            "name VARCHAR(30) NULL DEFAULT NULL," +
+            "tel VARCHAR(30) NULL DEFAULT NULL," +
+            "nl INT NULL DEFAULT NULL," +
+            "PRIMARY KEY (oid))");
+    }
+
+}