From 326ba6a93060794d640c6d580f6c61cfd21b00c1 Mon Sep 17 00:00:00 2001 From: lihongjie0209 Date: Thu, 18 Apr 2024 14:23:27 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=95=B0=E6=8D=AE=E5=AD=97?= =?UTF-8?q?=E5=85=B8=E7=BF=BB=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/cn/lihongjie/coal/DictCodeGen.java | 63 ++++ .../cn/lihongjie/coal/aop/ControllerAop.java | 7 +- .../cn/lihongjie/coal/base/dto/BaseDto.java | 4 + .../coal/base/entity/BaseEntity.java | 8 +- .../cn/lihongjie/coal/common/DictCode.java | 90 ++++++ .../dictionary/service/DictionaryService.java | 167 ++++++---- .../repository/OrganizationRepository.java | 7 + .../service/OrganizationService.java | 17 + .../coal/pojoProcessor/DictTranslate.java | 16 + .../coal/pojoProcessor/OrganizationName.java | 13 + .../coal/pojoProcessor/PojoProcessor.java | 305 ++++++++++++++++++ .../coal/pojoProcessor/UserName.java | 14 + .../coal/user/repository/UserRepository.java | 5 + .../coal/user/service/UserService.java | 38 ++- .../dto/WeightDeviceDataDto.java | 10 +- .../entity/WeightDeviceDataEntity.java | 17 +- 16 files changed, 691 insertions(+), 90 deletions(-) create mode 100644 src/main/java/cn/lihongjie/coal/DictCodeGen.java create mode 100644 src/main/java/cn/lihongjie/coal/common/DictCode.java create mode 100644 src/main/java/cn/lihongjie/coal/pojoProcessor/DictTranslate.java create mode 100644 src/main/java/cn/lihongjie/coal/pojoProcessor/OrganizationName.java create mode 100644 src/main/java/cn/lihongjie/coal/pojoProcessor/PojoProcessor.java create mode 100644 src/main/java/cn/lihongjie/coal/pojoProcessor/UserName.java diff --git a/src/main/java/cn/lihongjie/coal/DictCodeGen.java b/src/main/java/cn/lihongjie/coal/DictCodeGen.java new file mode 100644 index 00000000..b6629056 --- /dev/null +++ b/src/main/java/cn/lihongjie/coal/DictCodeGen.java @@ -0,0 +1,63 @@ +package cn.lihongjie.coal; + +import cn.lihongjie.coal.errorMsg.entity.ErrorMsgEntity; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.CaseFormat; +import com.squareup.javapoet.FieldSpec; +import com.squareup.javapoet.TypeSpec; + +import lombok.SneakyThrows; +import lombok.experimental.UtilityClass; + +import org.springframework.core.io.ClassPathResource; + +import java.io.InputStream; +import java.util.*; + +import javax.lang.model.element.Modifier; + +public class DictCodeGen { + + @SneakyThrows + public static void main(String[] args) { + + ClassPathResource classPathResource = new ClassPathResource("/config/dictionary.json"); + + ObjectMapper mapper = new ObjectMapper(); + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + + List errorMsgs; + + try (InputStream inputStream = classPathResource.getInputStream()) { + errorMsgs = mapper.readValue(inputStream, new TypeReference>() {}); + } + + TypeSpec.Builder builder = + TypeSpec.classBuilder("DictCode") + .addModifiers(Modifier.PUBLIC) + .addAnnotation(UtilityClass.class); + + for (ErrorMsgEntity errorMsg : errorMsgs) { + + builder.addField( + FieldSpec.builder( + String.class, + CaseFormat.LOWER_UNDERSCORE.to( + CaseFormat.UPPER_UNDERSCORE, + errorMsg.getCode().replace(".", "_")), + Modifier.PUBLIC, + Modifier.STATIC, + Modifier.FINAL) + .initializer("$S", errorMsg.getCode() ) + .build()); + } + + builder.build(); + + + Codegen.saveFile("cn.lihongjie.coal.common", builder.build()); + } +} diff --git a/src/main/java/cn/lihongjie/coal/aop/ControllerAop.java b/src/main/java/cn/lihongjie/coal/aop/ControllerAop.java index 69970ded..49624364 100644 --- a/src/main/java/cn/lihongjie/coal/aop/ControllerAop.java +++ b/src/main/java/cn/lihongjie/coal/aop/ControllerAop.java @@ -5,6 +5,7 @@ import cn.lihongjie.coal.base.dto.CommonDto; import cn.lihongjie.coal.base.entity.CommonEntity; import cn.lihongjie.coal.common.RequestUtils; import cn.lihongjie.coal.ip.IpQueryService; +import cn.lihongjie.coal.pojoProcessor.PojoProcessor; import cn.lihongjie.coal.session.SessionService; import cn.lihongjie.coal.syslog.entity.SysLogEntity; import cn.lihongjie.coal.syslog.service.SysLogService; @@ -63,6 +64,8 @@ public class ControllerAop { parser = new SpelExpressionParser(config); } + @Autowired PojoProcessor pojoProcessor; + @Pointcut("execution (* cn.lihongjie.coal.*.controller.*.*(..))") public void controllerMethods() {} @@ -80,7 +83,9 @@ public class ControllerAop { SysLogEntity sysLogEntity = createSysLog(method, request, proceedingJoinPoint.getArgs()); try { - return proceedingJoinPoint.proceed(); + Object proceed = proceedingJoinPoint.proceed(); + pojoProcessor.process(proceed, false); + return proceed; } catch (Throwable e) { diff --git a/src/main/java/cn/lihongjie/coal/base/dto/BaseDto.java b/src/main/java/cn/lihongjie/coal/base/dto/BaseDto.java index 2e02d1e9..ac047c16 100644 --- a/src/main/java/cn/lihongjie/coal/base/dto/BaseDto.java +++ b/src/main/java/cn/lihongjie/coal/base/dto/BaseDto.java @@ -1,5 +1,7 @@ package cn.lihongjie.coal.base.dto; +import cn.lihongjie.coal.pojoProcessor.UserName; + import lombok.Getter; import lombok.Setter; @@ -14,11 +16,13 @@ public abstract class BaseDto { private String createUserId; + @UserName private String createUserName; private LocalDateTime createTime; private String updateUserId; + @UserName private String updateUserName; private LocalDateTime updateTime; diff --git a/src/main/java/cn/lihongjie/coal/base/entity/BaseEntity.java b/src/main/java/cn/lihongjie/coal/base/entity/BaseEntity.java index 843b4309..d84f5174 100644 --- a/src/main/java/cn/lihongjie/coal/base/entity/BaseEntity.java +++ b/src/main/java/cn/lihongjie/coal/base/entity/BaseEntity.java @@ -29,8 +29,8 @@ public class BaseEntity { @Column(updatable = false) private String createUserId; - @Formula("(select tu.name from t_user tu where tu.id = create_user_id)") - private String createUserName; +// @Formula("(select tu.name from t_user tu where tu.id = create_user_id)") +// private String createUserName; @Comment("创建时间") @CreationTimestamp(source = SourceType.VM) @@ -40,8 +40,8 @@ public class BaseEntity { @Comment("更新用户ID") private String updateUserId; - @Formula("((select tu.name from t_user tu where tu.id = create_user_id))") - private String updateUserName; +// @Formula("((select tu.name from t_user tu where tu.id = create_user_id))") +// private String updateUserName; @Comment("更新时间") @UpdateTimestamp(source = SourceType.VM) diff --git a/src/main/java/cn/lihongjie/coal/common/DictCode.java b/src/main/java/cn/lihongjie/coal/common/DictCode.java new file mode 100644 index 00000000..7065f189 --- /dev/null +++ b/src/main/java/cn/lihongjie/coal/common/DictCode.java @@ -0,0 +1,90 @@ +package cn.lihongjie.coal.common; + +import lombok.experimental.UtilityClass; + +@UtilityClass +public class DictCode { + public static final String BANK = "bank"; + + public static final String METER_TYPE = "meter.type"; + + public static final String COMMON_STEP_STATUS = "common.step.status"; + + public static final String APPOINTMENT_STATUS = "appointment.status"; + + public static final String PURCHASEORDER_STATUS = "purchaseOrder.status"; + + public static final String NETDISK_ENTRYTYPE = "netDisk.entryType"; + + public static final String NOTEBOOK_CONTENTTYPE = "notebook.contentType"; + + public static final String CRONJOB_EXECSTATUS = "cronJob.execStatus"; + + public static final String COMMON_EXECSTATUS = "common.execStatus"; + + public static final String LOGINUSERHIS_LOGINSTATUS = "loginUserHis.loginStatus"; + + public static final String LOGINUSERHIS_LOGOUTTYPE = "loginUserHis.logoutType"; + + public static final String PERMISSION_TYPE = "permission.type"; + + public static final String STATUS_TYPE = "status.type"; + + public static final String SCRIPT_USAGE = "script.usage"; + + public static final String RESOURCE_TYPE = "resource.type"; + + public static final String DICT_TYPE = "dict.type"; + + public static final String DICT_COMPONENTTYPE = "dict.componentType"; + + public static final String SYSLOG_STATUS = "syslog.status"; + + public static final String COAL_TYPE = "coal.type"; + + public static final String ARCHIVESTATUS = "archiveStatus"; + + public static final String WAREHOUSE_RECEIPTTYPE = "warehouse.receiptType"; + + public static final String EMP_STATUS = "emp.status"; + + public static final String EMP_SALARY_ITEM_CONFIG_TYPE = "emp.salary.item.config.type"; + + public static final String EXCEL_TEMPLATE_TYPE = "excel.template.type"; + + public static final String EXCEL_GENERATOR_DATASOURCE_TYPE = "excel.generator.datasource.type"; + + public static final String DEVICE_WORKORDER_STATUS = "device.workOrder.status"; + + public static final String DEVICE_WORKORDER_TYPE = "device.workOrder.type"; + + public static final String EMP_RECORD_TYPE = "emp.record.type"; + + public static final String COALBLEND_COALTYPE = "coalBlend.coalType"; + + public static final String INVENTORYCHECK_TYPE = "inventoryCheck.type"; + + public static final String EMP_FAMILYMEMBER_RELATION = "emp.familyMember.relation"; + + public static final String COALPARAMETER_INPUTTYPE = "coalParameter.inputType"; + + public static final String COAL_BLENDTYPE = "coal.blendType"; + + public static final String SEX = "sex"; + + public static final String NATION = "nation"; + + public static final String MARRIAGE = "marriage"; + + public static final String EDUCATION = "education"; + + public static final String SALARYITEM_TYPE = "salaryItem.type"; + + public static final String SALARYITEM_INPUTTYPE = "salaryItem.inputType"; + + public static final String EM_DEVICE_TYPE = "em.device.type"; + + public static final String AC_DEVICE_TYPE = "ac.device.type"; + + public static final String THIRDACCOUNT_TYPE = "thirdAccount.type"; +} diff --git a/src/main/java/cn/lihongjie/coal/dictionary/service/DictionaryService.java b/src/main/java/cn/lihongjie/coal/dictionary/service/DictionaryService.java index 12df3f90..e77f48cb 100644 --- a/src/main/java/cn/lihongjie/coal/dictionary/service/DictionaryService.java +++ b/src/main/java/cn/lihongjie/coal/dictionary/service/DictionaryService.java @@ -21,15 +21,18 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import io.vavr.Function2; +import io.vavr.Tuple2; import jakarta.annotation.PostConstruct; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import jakarta.persistence.Query; +import jakarta.persistence.Tuple; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -40,17 +43,16 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StopWatch; import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; +import java.util.*; +import java.util.stream.Collectors; @Service @Slf4j @Transactional -public -class DictionaryService extends BaseService { +public class DictionaryService extends BaseService { @Autowired DictionaryRepository repository; @@ -218,65 +220,48 @@ class DictionaryService extends BaseService autoComplete(AutoCompleteRequest request) { - public List autoComplete(AutoCompleteRequest request){ + Query nativeQuery; + if (StringUtils.isNotEmpty(request.getOrganizationId())) { - Query nativeQuery; - if (StringUtils.isNotEmpty(request.getOrganizationId())){ - - nativeQuery = entityManager.createNativeQuery( - "select distinct " + - request.getFieldName() + - " from " + - request.getTableName() + - " where " + - " organization_id = '" + - request.getOrganizationId() + - "'" + - " and " + - request.getFieldName() + - " like '%" + - ObjectUtils.defaultIfNull(request.getQuery(), "") + - "%'"); - - }else { - - nativeQuery = entityManager.createNativeQuery( - - "select distinct " + - request.getFieldName() + - " from " + - request.getTableName() + - " where " + - request.getFieldName() + - " like '%" + - ObjectUtils.defaultIfNull(request.getQuery(), "") + - "%'"); + nativeQuery = + entityManager.createNativeQuery( + "select distinct " + + request.getFieldName() + + " from " + + request.getTableName() + + " where " + + " organization_id = '" + + request.getOrganizationId() + + "'" + + " and " + + request.getFieldName() + + " like '%" + + ObjectUtils.defaultIfNull(request.getQuery(), "") + + "%'"); + } else { + nativeQuery = + entityManager.createNativeQuery( + "select distinct " + + request.getFieldName() + + " from " + + request.getTableName() + + " where " + + request.getFieldName() + + " like '%" + + ObjectUtils.defaultIfNull(request.getQuery(), "") + + "%'"); } - return nativeQuery.getResultList().stream().map(x -> new TreeDto(null, null, x.toString(), null)).toList(); - - - - } - - public List getExcelValidation(String s) { - - - DictTreeRequest request = new DictTreeRequest(); - request.setCode(s); - DictionaryTreeDto tree = tree(request); - - ArrayList list = new ArrayList<>(); - - TreeUtils.dfsList(tree.getTree(), (TreeDto x )->x.getChildren(), object -> list.add(object.getCurrent().getName()), (TreeDto x )->x.getId()); - - return list; + return nativeQuery.getResultList().stream() + .map(x -> new TreeDto(null, null, x.toString(), null)) + .toList(); } public Function2 getTranslator() { @@ -286,8 +271,72 @@ class DictionaryService extends BaseService getExcelValidation(String s) { + + DictTreeRequest request = new DictTreeRequest(); + request.setCode(s); + DictionaryTreeDto tree = tree(request); + + ArrayList list = new ArrayList<>(); + + TreeUtils.dfsList( + tree.getTree(), + (TreeDto x) -> x.getChildren(), + object -> list.add(object.getCurrent().getName()), + (TreeDto x) -> x.getId()); + + return list; + } + + public Map, String> getDictNameMap(Set> tuple2s) { + + if (CollectionUtils.isEmpty(tuple2s)) { + return Collections.emptyMap(); + } + + StopWatch stopWatch = new StopWatch(); + + String where = tuple2s.stream() + .map(x -> "(d.code = '" + x._1 + "' and di.code = '" + x._2 + "')") + .reduce((x, y) -> x + " or " + y) + .get(); + + stopWatch.start("createNativeQuery"); + Query nativeQuery = em.createNativeQuery( + """ + select d.code as dict_key, di.code as dict_code, di.name as dict_name from t_dictionary d inner join t_dictionary_item di on d.id = di.dictionary_id + where + + + """ + where, Tuple.class); + + + stopWatch.stop(); + + stopWatch.start("getResultList"); + List resultList = nativeQuery.getResultList(); + + + stopWatch.stop(); + + stopWatch.start("collect"); + + Map, String> collect = + resultList.stream() + .collect( + Collectors.toMap( + x -> + new Tuple2<>( + x.get("dict_key").toString(), + x.get("dict_code").toString()), + x -> x.get("dict_name").toString())); + + stopWatch.stop(); + +// log.info(stopWatch.prettyPrint()); + return collect; + } } diff --git a/src/main/java/cn/lihongjie/coal/organization/repository/OrganizationRepository.java b/src/main/java/cn/lihongjie/coal/organization/repository/OrganizationRepository.java index 4dced037..cc3a2662 100644 --- a/src/main/java/cn/lihongjie/coal/organization/repository/OrganizationRepository.java +++ b/src/main/java/cn/lihongjie/coal/organization/repository/OrganizationRepository.java @@ -3,11 +3,18 @@ package cn.lihongjie.coal.organization.repository; import cn.lihongjie.coal.base.dao.BaseRepository; import cn.lihongjie.coal.organization.entity.OrganizationEntity; +import org.springframework.data.jpa.repository.Query; import org.springframework.lang.Nullable; import org.springframework.stereotype.Repository; +import java.util.List; +import java.util.Set; + @Repository public interface OrganizationRepository extends BaseRepository { @Nullable OrganizationEntity findByCode(String code); + + @Query("select u.id || ',' || u.name from OrganizationEntity u where u.id in ?1") + List findNamesByIds(Set ids); } diff --git a/src/main/java/cn/lihongjie/coal/organization/service/OrganizationService.java b/src/main/java/cn/lihongjie/coal/organization/service/OrganizationService.java index 72fdfef0..0082c707 100644 --- a/src/main/java/cn/lihongjie/coal/organization/service/OrganizationService.java +++ b/src/main/java/cn/lihongjie/coal/organization/service/OrganizationService.java @@ -14,6 +14,8 @@ import cn.lihongjie.coal.rabbitmq.RabbitMQService; import cn.lihongjie.coal.user.dto.CreateOrgAdminDto; import cn.lihongjie.coal.user.service.UserService; +import io.vavr.collection.Stream; + import jakarta.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; @@ -29,6 +31,9 @@ import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; @Service @Slf4j @@ -121,4 +126,16 @@ class OrganizationService extends BaseService getIdNameMap(Set strings) { + + List names = this.repository.findNamesByIds(strings); + + Map javaMap = Stream.ofAll(names).toMap(x -> x.split(",")[0], x -> x.split(",")[1]).toJavaMap(); + + strings.forEach(x -> javaMap.putIfAbsent(x, null)); + + return javaMap; + + } } diff --git a/src/main/java/cn/lihongjie/coal/pojoProcessor/DictTranslate.java b/src/main/java/cn/lihongjie/coal/pojoProcessor/DictTranslate.java new file mode 100644 index 00000000..205a90fd --- /dev/null +++ b/src/main/java/cn/lihongjie/coal/pojoProcessor/DictTranslate.java @@ -0,0 +1,16 @@ +package cn.lihongjie.coal.pojoProcessor; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) +@Target(java.lang.annotation.ElementType.FIELD) +public @interface DictTranslate { + + String ref() default "#auto"; + + String dictKey(); + + + +} diff --git a/src/main/java/cn/lihongjie/coal/pojoProcessor/OrganizationName.java b/src/main/java/cn/lihongjie/coal/pojoProcessor/OrganizationName.java new file mode 100644 index 00000000..677940e4 --- /dev/null +++ b/src/main/java/cn/lihongjie/coal/pojoProcessor/OrganizationName.java @@ -0,0 +1,13 @@ +package cn.lihongjie.coal.pojoProcessor; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) +@Target(java.lang.annotation.ElementType.FIELD) +public @interface OrganizationName { + + + String ref() default "#auto"; + +} diff --git a/src/main/java/cn/lihongjie/coal/pojoProcessor/PojoProcessor.java b/src/main/java/cn/lihongjie/coal/pojoProcessor/PojoProcessor.java new file mode 100644 index 00000000..74c65b52 --- /dev/null +++ b/src/main/java/cn/lihongjie/coal/pojoProcessor/PojoProcessor.java @@ -0,0 +1,305 @@ +package cn.lihongjie.coal.pojoProcessor; + +import cn.lihongjie.coal.base.dto.R; +import cn.lihongjie.coal.dictionary.service.DictionaryService; +import cn.lihongjie.coal.organization.service.OrganizationService; +import cn.lihongjie.coal.user.service.UserService; + +import io.vavr.Tuple2; + +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; + +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.StopWatch; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.*; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +@Service +@Slf4j +public class PojoProcessor { + + @Autowired UserService userService; + + @Autowired OrganizationService organizationService; + + @Autowired DictionaryService dictionaryService; + + @SneakyThrows + public void process(Object pojo, boolean logStopWatch) { + + new PojoProcessorCtx(pojo, logStopWatch).process(); + } + + public class PojoProcessorCtx { + + private final Map> userNameActions = new HashMap<>(); + private final Map> organizationNameActions = new HashMap<>(); + private final Map, Consumer> dictActions = new HashMap<>(); + private final boolean logStopWatch; + private StopWatch stopWatch; + private final Object pojo; + private final Set seen = new HashSet<>(); + + private final Map> allFieldsMap = new HashMap<>(); + + public PojoProcessorCtx(Object pojo) { + this(pojo, false); + } + + public PojoProcessorCtx(Object pojo, boolean logStopWatch) { + this.pojo = pojo; + this.logStopWatch = logStopWatch; + } + + private static boolean isJdkClass(Class cls) { + return cls.getName().startsWith("java."); + } + + public static boolean isContainer(Class cls) { + return cls.isArray() + || Iterable.class.isAssignableFrom(cls) + || Map.class.isAssignableFrom(cls) + || Optional.class.isAssignableFrom(cls) + || R.class.isAssignableFrom(cls); + } + + @SneakyThrows + public void process() { + + if (this.pojo == null) { + return; + } + stopWatch = new StopWatch("process pojo " + pojo.getClass().getName()); + + stopWatch.start("collect actions"); + collectActions(this.pojo); + stopWatch.stop(); + + doActions(); + + if (logStopWatch) { + + log.info(stopWatch.prettyPrint()); + } + } + + @SneakyThrows + private void collectActions(Object pojo) { + + if (pojo == null) { + return; + } + + if (pojo instanceof Iterable it) { + it.forEach(this::collectActions); + return; + } else if (pojo instanceof Map map) { + map.values().forEach(this::collectActions); + return; + } else if (pojo instanceof Optional optional) { + optional.ifPresent(this::collectActions); + return; + } else if (pojo instanceof Object[] array) { + Arrays.stream(array).forEach(this::collectActions); + return; + } else if (pojo instanceof R r) { + collectActions(r.getData()); + return; + } + + Class cls = pojo.getClass(); + // process pojo + + // check if base java type, use package name + if (isJdkClass(cls)) { + return; + } + + if (!seen.add(pojo)) { + return; + } + + List allFields = allFieldsMap.computeIfAbsent(cls, FieldUtils::getAllFieldsList); + + Map> fieldNameMap = + allFields.stream().collect(Collectors.groupingBy(Field::getName)); + + for (Field field : allFields) { + if (Modifier.isStatic(field.getModifiers())) { + continue; + } + if (field.isAnnotationPresent(UserName.class) + || field.isAnnotationPresent(OrganizationName.class)) { + + UserName userName = field.getAnnotation(UserName.class); + OrganizationName organizationName = field.getAnnotation(OrganizationName.class); + + String ref = userName == null ? organizationName.ref() : userName.ref(); + + Field refField = null; + + if (ref.equalsIgnoreCase("#auto")) { + + if (field.getName().endsWith("Name")) { + String refName = + field.getName().substring(0, field.getName().length() - 4) + + "Id"; + if (!fieldNameMap.containsKey(refName)) { + throw new RuntimeException( + "ref field not found " + field.getName() + " " + ref); + } + + refField = fieldNameMap.get(refName).get(0); + } + + } else { + + if (!fieldNameMap.containsKey("ref")) { + throw new RuntimeException( + "ref field not found " + field.getName() + " " + ref); + } + + refField = fieldNameMap.get("ref").get(0); + } + + Object val = FieldUtils.readField(refField, pojo, true); + + if (val != null) { + + (userName == null ? organizationNameActions : userNameActions) + .merge( + val.toString(), + (String name) -> { + try { + FieldUtils.writeField(field, pojo, name, true); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }, + Consumer::andThen); + } + } else if (field.isAnnotationPresent(DictTranslate.class)) { + + DictTranslate dictTranslate = field.getAnnotation(DictTranslate.class); + String dictKey = dictTranslate.dictKey(); + + String ref = dictTranslate.ref(); + Field refField = null; + if (ref.equalsIgnoreCase("#auto")) { + + if (field.getName().endsWith("Name")) { + String refName = + field.getName().substring(0, field.getName().length() - 4); + if (!fieldNameMap.containsKey(refName)) { + throw new RuntimeException( + "ref field not found " + field.getName() + " " + ref); + } + + refField = fieldNameMap.get(refName).get(0); + } + + } else { + + if (!fieldNameMap.containsKey("ref")) { + throw new RuntimeException( + "ref field not found " + field.getName() + " " + ref); + } + + refField = fieldNameMap.get("ref").get(0); + } + + + + + Object val = FieldUtils.readField(refField, pojo, true); + + String dictCode = val == null ? "" : val.toString(); + + if (StringUtils.isNotEmpty(dictCode)) { + dictActions.merge( + new Tuple2<>(dictKey, dictCode), + (String name) -> { + try { + FieldUtils.writeField(field, pojo, name, true); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }, + Consumer::andThen); + } + + } else { + + if (isContainer(field.getType()) || !isJdkClass(field.getType())) { + + Object val = FieldUtils.readField(field, pojo, true); + collectActions(val); + } + } + } + } + + private void doActions() { + + if (MapUtils.isNotEmpty(userNameActions)) { + + stopWatch.start("userService.getIdNameMap " + userNameActions.size()); + Map userIdNameMap = + userService.getIdNameMap(userNameActions.keySet()); + + stopWatch.stop(); + + stopWatch.start("do userNameActions " + userNameActions.size()); + userNameActions.forEach( + (k, v) -> { + v.accept(userIdNameMap.get(k)); + }); + + stopWatch.stop(); + } + + if (MapUtils.isNotEmpty(organizationNameActions)) { + stopWatch.start( + "organizationService.getIdNameMap " + organizationNameActions.size()); + Map organizationIdNameMap = + organizationService.getIdNameMap(organizationNameActions.keySet()); + + stopWatch.stop(); + + stopWatch.start("do organizationNameActions " + organizationNameActions.size()); + organizationNameActions.forEach( + (k, v) -> { + v.accept(organizationIdNameMap.get(k)); + }); + + stopWatch.stop(); + } + + if (MapUtils.isNotEmpty(dictActions)) { + stopWatch.start("dictionaryService.getDictNameMap " + dictActions.size()); + + Map, String> dictMap = + dictionaryService.getDictNameMap(dictActions.keySet()); + + stopWatch.stop(); + + stopWatch.start("do dictActions " + dictActions.size()); + dictActions.forEach( + (k, v) -> { + v.accept(dictMap.get(k)); + }); + + stopWatch.stop(); + } + } + } +} diff --git a/src/main/java/cn/lihongjie/coal/pojoProcessor/UserName.java b/src/main/java/cn/lihongjie/coal/pojoProcessor/UserName.java new file mode 100644 index 00000000..3ee0ee68 --- /dev/null +++ b/src/main/java/cn/lihongjie/coal/pojoProcessor/UserName.java @@ -0,0 +1,14 @@ +package cn.lihongjie.coal.pojoProcessor; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; +import java.util.*; + +@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) +@Target(java.lang.annotation.ElementType.FIELD) +public @interface UserName { + + + String ref() default "#auto"; + +} diff --git a/src/main/java/cn/lihongjie/coal/user/repository/UserRepository.java b/src/main/java/cn/lihongjie/coal/user/repository/UserRepository.java index c3296cf8..fa49618a 100644 --- a/src/main/java/cn/lihongjie/coal/user/repository/UserRepository.java +++ b/src/main/java/cn/lihongjie/coal/user/repository/UserRepository.java @@ -6,6 +6,9 @@ import cn.lihongjie.coal.user.entity.UserEntity; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; +import java.util.List; +import java.util.Set; + @Repository public interface UserRepository extends BaseRepository { @@ -19,4 +22,6 @@ public interface UserRepository extends BaseRepository { @Query("select count(u) > 0 from UserEntity u join u.roles r join r.permissions p join p.resources pr where u.id = ?1 and pr.id = ?2") boolean hasResource(String userId, String resourceId); + @Query("select u.id || ',' || u.name from UserEntity u where u.id in ?1") + List findNamesByIds(Set ids); } diff --git a/src/main/java/cn/lihongjie/coal/user/service/UserService.java b/src/main/java/cn/lihongjie/coal/user/service/UserService.java index 0097eae2..7a28f965 100644 --- a/src/main/java/cn/lihongjie/coal/user/service/UserService.java +++ b/src/main/java/cn/lihongjie/coal/user/service/UserService.java @@ -56,7 +56,9 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StopWatch; import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; @Service @@ -372,18 +374,22 @@ public class UserService extends BaseService { } public UserEntity findUniqUserByPhone(final String phone) { - List users = findAll(new Specification() { - @Override - public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { - return criteriaBuilder.equal(root.get("phone"), phone); - } - }); - if (CollectionUtils.isEmpty(users)){ + List users = + findAll( + new Specification() { + @Override + public Predicate toPredicate( + Root root, + CriteriaQuery query, + CriteriaBuilder criteriaBuilder) { + return criteriaBuilder.equal(root.get("phone"), phone); + } + }); + if (CollectionUtils.isEmpty(users)) { throw new BizException("手机号不存在"); } - - if (users.size() > 1){ + if (users.size() > 1) { throw new BizException("手机号重复"); } @@ -395,4 +401,18 @@ public class UserService extends BaseService { return this.repository.hasResource(userId, resourceId); } + + public Map getIdNameMap(Set strings) { + + strings = Stream.ofAll(strings).filter(StringUtils::isNotBlank).toJavaSet(); + if (strings.isEmpty()) return Map.of(); + + List names = this.repository.findNamesByIds(strings); + + Map javaMap = Stream.ofAll(names).toMap(x -> x.split(",")[0], x -> x.split(",")[1]).toJavaMap(); + + strings.forEach(x -> javaMap.putIfAbsent(x, null)); + + return javaMap; + } } diff --git a/src/main/java/cn/lihongjie/coal/weightDeviceData/dto/WeightDeviceDataDto.java b/src/main/java/cn/lihongjie/coal/weightDeviceData/dto/WeightDeviceDataDto.java index 5a52a41d..4b4b0a00 100644 --- a/src/main/java/cn/lihongjie/coal/weightDeviceData/dto/WeightDeviceDataDto.java +++ b/src/main/java/cn/lihongjie/coal/weightDeviceData/dto/WeightDeviceDataDto.java @@ -1,6 +1,7 @@ package cn.lihongjie.coal.weightDeviceData.dto; import cn.lihongjie.coal.base.dto.OrgCommonDto; +import cn.lihongjie.coal.pojoProcessor.DictTranslate; import cn.lihongjie.coal.weightDevice.dto.WeightDeviceDto; import jakarta.persistence.FetchType; @@ -10,7 +11,6 @@ import lombok.Data; import org.hibernate.annotations.ColumnDefault; import org.hibernate.annotations.Comment; -import org.hibernate.annotations.Formula; import java.time.LocalDateTime; @@ -281,12 +281,6 @@ public class WeightDeviceDataDto extends OrgCommonDto { @ColumnDefault("'0'") private String archiveStatus = "0"; - @Formula( - "(select i.name\n" - + "from t_dictionary d,\n" - + " t_dictionary_item i\n" - + "where d.id = i.dictionary_id\n" - + " and d.code = 'archiveStatus'\n" - + " and i.code = archive_status)") + @DictTranslate(dictKey = "archiveStatus") private String archiveStatusName; } diff --git a/src/main/java/cn/lihongjie/coal/weightDeviceData/entity/WeightDeviceDataEntity.java b/src/main/java/cn/lihongjie/coal/weightDeviceData/entity/WeightDeviceDataEntity.java index b9db00c4..ea08f6f4 100644 --- a/src/main/java/cn/lihongjie/coal/weightDeviceData/entity/WeightDeviceDataEntity.java +++ b/src/main/java/cn/lihongjie/coal/weightDeviceData/entity/WeightDeviceDataEntity.java @@ -11,7 +11,6 @@ import lombok.Data; import org.hibernate.annotations.ColumnDefault; import org.hibernate.annotations.Comment; -import org.hibernate.annotations.Formula; import java.time.LocalDateTime; @@ -460,12 +459,12 @@ public class WeightDeviceDataEntity extends OrgCommonEntity { @ColumnDefault("'0'") private String archiveStatus = "0"; - @Formula( - "(select i.name\n" - + "from t_dictionary d,\n" - + " t_dictionary_item i\n" - + "where d.id = i.dictionary_id\n" - + " and d.code = 'archiveStatus'\n" - + " and i.code = archive_status)") - private String archiveStatusName; +// @Formula( +// "(select i.name\n" +// + "from t_dictionary d,\n" +// + " t_dictionary_item i\n" +// + "where d.id = i.dictionary_id\n" +// + " and d.code = 'archiveStatus'\n" +// + " and i.code = archive_status)") +// private String archiveStatusName; }