Browse Source

进一步封装tableStore,使开发更关注业务

tanzhongran 3 years ago
parent
commit
bad79d2b10

+ 105 - 0
abi-cloud-qr-platform-common/src/main/java/com/abi/task/common/tablestore/TableStorePlusUtils.java

@@ -0,0 +1,105 @@
+package com.abi.task.common.tablestore;
+
+import cn.hutool.core.date.DateUtil;
+import com.abi.task.common.api.exception.BusinessException;
+import com.abi.task.common.tablestore.common.TableStore;
+import com.abi.task.common.tablestore.common.TableStoreEntity;
+import com.abi.task.common.utils.IStringUtil;
+import com.abi.task.common.utils.TableStoreUtils;
+import com.alicloud.openservices.tablestore.model.Column;
+import com.alicloud.openservices.tablestore.model.ColumnValue;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * 进一步封装的tablestore工具类
+ */
+@Component
+@Slf4j
+public class TableStorePlusUtils {
+
+    @Autowired
+    private TableStoreUtils tableStoreUtils;
+
+    /**
+     * 存储一行数据(如果主键key相同,则覆盖)
+     * @param entity
+     * @throws IllegalAccessException
+     */
+    public void putRow(TableStoreEntity entity){
+        try {
+            List<Column> columns = new ArrayList<>();
+            //表名
+            TableStore tableStore = entity.getClass().getAnnotation(TableStore.class);
+            String tableName = tableStore.tableName();
+            if (StringUtils.isBlank(tableName)) {
+                throw new BusinessException("存储表名为空");
+            }
+            //主键
+            String primaryKeyName = tableStore.primaryKeyName();
+            if (StringUtils.isBlank(primaryKeyName)) {
+                throw new BusinessException("存储主键为空");
+            }
+            //主键的驼峰转下划线
+            primaryKeyName = IStringUtil.camelToUnderline(primaryKeyName);
+            //主键的值
+            String primaryKeyVal = null;
+
+
+            //column列表  循环放入字段
+            Field[] fields = entity.getClass().getDeclaredFields();
+            for (Field field : fields) {
+                String fieldName = field.getName();
+                String underlineFieldName = IStringUtil.camelToUnderline(fieldName);
+                //获取method
+                Method method = entity.getClass().getMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1));
+                if (method == null){
+                    throw new BusinessException("get方法不存在");
+                }
+                //反射调用拿到结果
+                Object fieldValue = method.invoke(entity);
+                //如果是主键则赋值,主键值不放入column,不然阿里会报错
+                if (primaryKeyVal == null && underlineFieldName.equals(primaryKeyName)) {
+                    primaryKeyVal = (String) fieldValue;
+                    continue;
+                }
+                //放入table的column
+                Column column = null;
+                if (fieldValue instanceof String) {
+                    column = new Column(underlineFieldName, ColumnValue.fromString(String.valueOf(fieldValue)));
+                } else if (fieldValue instanceof Integer) {
+                    column = new Column(underlineFieldName, ColumnValue.fromLong(Long.valueOf((Integer) fieldValue)));
+                } else if (fieldValue instanceof Long) {
+                    column = new Column(underlineFieldName, ColumnValue.fromLong((Long) fieldValue));
+                } else if (fieldValue instanceof Double) {
+                    column = new Column(underlineFieldName, ColumnValue.fromDouble((Double) fieldValue));
+                } else if (fieldValue instanceof Boolean) {
+                    column = new Column(underlineFieldName, ColumnValue.fromBoolean((Boolean) fieldValue));
+                } else if (fieldValue instanceof Date) {
+                    column = new Column(underlineFieldName, ColumnValue.fromString(DateUtil.format((Date) fieldValue, "yyyy-MM-dd HH:mm:ss")));
+                } else if (fieldValue instanceof LocalDateTime) {
+                    column = new Column(underlineFieldName, ColumnValue.fromString(DateUtil.format((LocalDateTime) fieldValue, "yyyy-MM-dd HH:mm:ss")));
+                } else {
+                    log.info("不识别的字段类型 fieldName=" + fieldName);
+                    continue;
+                }
+                columns.add(column);
+            }
+
+            tableStoreUtils.putRow(primaryKeyName, primaryKeyVal, tableName, columns);
+        }catch (Exception e){
+            log.info("setRow error",e);
+            throw new BusinessException("存储table异常");
+        }
+    }
+
+}

+ 17 - 0
abi-cloud-qr-platform-common/src/main/java/com/abi/task/common/tablestore/common/TableStore.java

@@ -0,0 +1,17 @@
+package com.abi.task.common.tablestore.common;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * tableStore注解
+ * @author AndyTan
+ */
+@Target(ElementType.TYPE)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface TableStore {
+    String tableName();
+    String primaryKeyName();
+}

+ 4 - 0
abi-cloud-qr-platform-common/src/main/java/com/abi/task/common/tablestore/common/TableStoreEntity.java

@@ -0,0 +1,4 @@
+package com.abi.task.common.tablestore.common;
+
+public interface TableStoreEntity {
+}

+ 29 - 0
abi-cloud-qr-platform-common/src/main/java/com/abi/task/common/tablestore/entity/DemoEntity.java

@@ -0,0 +1,29 @@
+package com.abi.task.common.tablestore.entity;
+
+import com.abi.task.common.tablestore.common.TableStore;
+import com.abi.task.common.tablestore.common.TableStoreEntity;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+import java.time.LocalDateTime;
+
+@Data
+@NoArgsConstructor
+@TableStore(tableName = "iqms_qr_code",primaryKeyName = "qrCode")
+public class DemoEntity implements TableStoreEntity {
+
+    private String qrCode;
+
+    private String actName;
+
+    private Double payAmount;
+
+    private LocalDateTime currentTime;
+
+    private Long userId;
+
+    private Integer activeCount;
+
+    private Boolean isDog;
+
+}

+ 66 - 0
abi-cloud-qr-platform-common/src/main/java/com/abi/task/common/utils/IStringUtil.java

@@ -0,0 +1,66 @@
+package com.abi.task.common.utils;
+
+import org.apache.commons.lang3.StringUtils;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * String工具类
+ * @author 字符串工具类
+ */
+public class IStringUtil {
+
+    /**
+     * 识别驼峰大写字母的正则
+     */
+    private static final Pattern HUMP_PATTERN = Pattern.compile("[A-Z]");
+
+    /**
+     * 驼峰转下划线
+     * @param camelStr
+     * @return
+     */
+    public static String camelToUnderline(String camelStr){
+        //PlayGame => play_game
+        if(StringUtils.isBlank(camelStr)){
+            return camelStr;
+        }
+
+        //1-如果首字母是大写则转化为小写
+        camelStr = camelStr.substring(0,1).toLowerCase()+camelStr.substring(1);
+
+        //2-将大写字母转化为_x : xxXxx => xx_xxx
+        Matcher matcher = HUMP_PATTERN.matcher(camelStr);
+        StringBuffer sb = new StringBuffer();
+        while (matcher.find()) {
+            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
+        }
+        matcher.appendTail(sb);
+        String underline = sb.toString();
+
+        return underline;
+    }
+
+    /**
+     * 下划线转驼峰
+     * @param underlineStr
+     * @return
+     */
+    public static String underlineToCamel(String underlineStr){
+        if(StringUtils.isBlank(underlineStr)){
+            return underlineStr;
+        }
+
+        String[] strArr = underlineStr.split("_");
+        StringBuffer camelSb = new StringBuffer();
+
+        for(String str:strArr){
+            String strLow = str.toLowerCase();
+            camelSb.append(strLow.substring(0,1).toUpperCase()+strLow.substring(1));
+        }
+
+        return camelSb.substring(0,1).toLowerCase()+camelSb.substring(1);
+    }
+
+}

+ 1 - 2
abi-cloud-qr-platform-common/src/main/java/com/abi/task/common/utils/TableStoreUtils.java

@@ -220,8 +220,7 @@ public class TableStoreUtils {
         return criteria;
     }
 
-    public RowUpdateChange updateChange(String primaryKeyName, String pkValue, String tableName) {
-
+    private RowUpdateChange updateChange(String primaryKeyName, String pkValue, String tableName) {
         //构造主键。
         PrimaryKeyBuilder primaryKeyBuilder = PrimaryKeyBuilder.createPrimaryKeyBuilder();
         primaryKeyBuilder.addPrimaryKeyColumn(primaryKeyName, PrimaryKeyValue.fromString(pkValue));

+ 35 - 0
abi-cloud-qr-platform-server/src/test/java/com/abi/qms/platform/TableStorePlusTest.java

@@ -0,0 +1,35 @@
+package com.abi.qms.platform;
+import java.time.LocalDateTime;
+
+import com.abi.task.common.tablestore.TableStorePlusUtils;
+import com.abi.task.common.tablestore.entity.DemoEntity;
+import lombok.extern.slf4j.Slf4j;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+
+@SpringBootTest
+@Slf4j
+public class TableStorePlusTest {
+
+    @Autowired
+    private TableStorePlusUtils tableStorePlusUtils;
+
+    @Test
+    public void testAddRow(){
+        DemoEntity entity = new DemoEntity();
+        entity.setQrCode("10293827182717");
+        entity.setActName("活动1");
+        entity.setPayAmount(990.12);
+        entity.setCurrentTime(LocalDateTime.now());
+        entity.setUserId(10001L);
+        entity.setActiveCount(33);
+        entity.setIsDog(false);
+
+        tableStorePlusUtils.putRow(entity);
+
+    }
+
+
+
+}