refactor:queryDsl工具类完善

V0.5.x
Longjun.Tu 2023-05-26 17:59:58 +08:00
parent 783eac5c45
commit 15b560a5f2
44 changed files with 525 additions and 470 deletions

View File

@ -1,5 +1,10 @@
package cc.iotkit.common.api;
import cc.iotkit.common.utils.SnowflakeIdGeneratorUtil;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.util.Map;
import lombok.Data;
import lombok.EqualsAndHashCode;
@ -18,22 +23,24 @@ public class PageRequest<T> extends Request<T> implements Serializable {
/**
*
*/
@Min(1)
@NotNull
private Integer pageSize;
/**
*
*/
@Min(1)
@Max(100)
@NotNull
private Integer pageNum;
/**
*
* key valuedescasc
*/
private String orderByColumn;
private Map<String,String> sortMap;
/**
* descasc
*/
private String isAsc;
/**
*
@ -41,8 +48,38 @@ public class PageRequest<T> extends Request<T> implements Serializable {
public static final int DEFAULT_PAGE_NUM = 1;
/**
*
*
*/
public static final int DEFAULT_PAGE_SIZE = Integer.MAX_VALUE;
public static final int DEFAULT_PAGE_SIZE = 20;
public static <T> PageRequest<T> of(T data) {
PageRequest<T> pageRequest = new PageRequest<>();
pageRequest.setPageSize(DEFAULT_PAGE_SIZE);
pageRequest.setPageNum(DEFAULT_PAGE_NUM);
pageRequest.setData(data);
pageRequest.setRequestId(String.valueOf(SnowflakeIdGeneratorUtil.getInstanceSnowflake().nextId()));
return pageRequest;
}
public static <DTO> PageRequest<DTO> request2PageRequest(Request<DTO> request) {
PageRequest<DTO> pageRequest = new PageRequest<>();
pageRequest.setData(request.getData());
pageRequest.setPageNum(DEFAULT_PAGE_NUM);
pageRequest.setPageSize(DEFAULT_PAGE_SIZE);
pageRequest.setRequestId(request.getRequestId());
return pageRequest;
}
public static <DTO> PageRequest<DTO> copyPageRequest(PageRequest query,DTO data) {
PageRequest<DTO> pageRequest = new PageRequest<>();
pageRequest.setData(data);
pageRequest.setPageNum(query.getPageNum());
pageRequest.setPageSize(query.getPageSize());
pageRequest.setRequestId(query.getRequestId());
pageRequest.setSortMap(query.getSortMap());
return pageRequest;
}
}

View File

@ -10,6 +10,6 @@ import lombok.Data;
*/
@Data
public class PageRequestEmpty {
private Integer page = 1;
private Integer size = 20;
private Integer pageNum = 1;
private Integer pageSize = 20;
}

View File

@ -1,5 +1,8 @@
package cc.iotkit.common.api;
import cc.iotkit.common.utils.SnowflakeIdGeneratorUtil;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.io.Serializable;
@ -13,12 +16,15 @@ import java.util.UUID;
*/
@Data
public class Request<T> extends RequestEmpty implements Serializable {
private T data;
@Valid
@NotNull
private T data;
public static <T> Request<T> of(T data) {
Request<T> request = new Request();
Request<T> request = new Request<>();
request.setData(data);
request.setRequestId(UUID.randomUUID().toString());
request.setRequestId(String.valueOf(SnowflakeIdGeneratorUtil.getInstanceSnowflake().nextId()));
return request;
}
}

View File

@ -1,5 +1,8 @@
package cc.iotkit.common.api;
import cc.iotkit.common.utils.SnowflakeIdGeneratorUtil;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import java.io.Serializable;
@ -14,11 +17,12 @@ import java.util.UUID;
@Data
public class RequestEmpty implements Serializable {
@NotBlank
private String requestId;
public static RequestEmpty of() {
RequestEmpty request = new RequestEmpty();
request.setRequestId(UUID.randomUUID().toString());
request.setRequestId(String.valueOf(SnowflakeIdGeneratorUtil.getInstanceSnowflake().nextId()));
return request;
}

View File

@ -16,6 +16,8 @@ public enum ErrCode implements IEnum {
NOT_FOUND(10000006, "请求资源不存在"),
FORBIDDEN(10000007, "请求被拒绝"),
UNAUTHORIZED_EXCEPTION(10000008, "未授权访问"),
UNSUPPORTED_OPERATION_EXCEPTION(10000009, "方法未实现"),
DATA_NOT_EXIST(10000010, "数据不存在"),
/**
*

View File

@ -29,7 +29,7 @@ public class BizException extends RuntimeException {
/**
*
*/
private String code;
private Integer code;
/**
*
@ -38,7 +38,7 @@ public class BizException extends RuntimeException {
public BizException(String message) {
super(message);
this.code = ErrCode.SYSTEM_EXCEPTION.getValue();
this.code = ErrCode.SYSTEM_EXCEPTION.getKey();
}
/**
@ -48,6 +48,7 @@ public class BizException extends RuntimeException {
*/
public BizException(ErrCode errCode) {
this.message = errCode.getValue();
this.code = errCode.getKey();
}
public BizException(ErrCode errCode, Throwable cause) {
@ -57,7 +58,7 @@ public class BizException extends RuntimeException {
public BizException(ErrCode errCode, String message) {
this.message = message;
this.code = errCode.getValue();
this.code = errCode.getKey();
}
public BizException(String message, Throwable cause) {

View File

@ -0,0 +1,9 @@
package cc.iotkit.common.validate;
/**
* delete
*
* @author Lion Li
*/
public interface DeleteGroup {
}

View File

@ -9,9 +9,11 @@
*/
package cc.iotkit.data;
import cc.iotkit.common.api.PageRequest;
import cc.iotkit.model.Id;
import cc.iotkit.common.api.Paging;
import java.util.Collection;
import java.util.List;
/**
@ -24,15 +26,22 @@ public interface ICommonData<T extends Id<ID>, ID> {
*/
T findById(ID id);
/**
* ID
*/
List<T> findByIds(Collection<ID> id);
/**
* id
*/
T save(T data);
/**
*
*
*/
T add(T data);
void batchSave(List<T> data);
/**
* id
@ -42,7 +51,7 @@ public interface ICommonData<T extends Id<ID>, ID> {
/**
* id
*/
void deleteByIds(ID[] ids);
void deleteByIds(Collection<ID> ids);
/**
*
@ -56,9 +65,17 @@ public interface ICommonData<T extends Id<ID>, ID> {
/**
*
*
* @param page 0
* @param size
*/
Paging<T> findAll(int page, int size);
Paging<T> findAll(PageRequest<T> pageRequest);
/**
*
*/
List<T> findAllByCondition(T data);
/**
*
*/
T findOneByCondition(T data);
}

View File

@ -1,5 +1,7 @@
package cc.iotkit.data.system;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.data.ICommonData;
import cc.iotkit.model.system.SysConfig;
@ -11,8 +13,4 @@ import cc.iotkit.model.system.SysConfig;
*/
public interface ISysConfigData extends ICommonData<SysConfig, Long> {
Paging<SysConfig> findConfigs(SysConfig query);
SysConfig findByConfigKey(String configKey);
}

View File

@ -34,11 +34,6 @@ public class CategoryDataCache implements ICategoryData {
return data;
}
@Override
public Category add(Category data) {
return categoryData.add(data);
}
@Override
public void deleteById(String s) {
categoryData.deleteById(s);

View File

@ -36,10 +36,6 @@ public class AlertConfigDataImpl implements IAlertConfigData {
return data;
}
@Override
public AlertConfig add(AlertConfig data) {
return null;
}
@Override
public void deleteById(String s) {

View File

@ -34,10 +34,6 @@ public class AlertRecordDataImpl implements IAlertRecordData {
return null;
}
@Override
public AlertRecord add(AlertRecord data) {
return null;
}
@Override
public void deleteById(String s) {

View File

@ -42,13 +42,6 @@ public class CategoryDataImpl implements ICategoryData {
return data;
}
@Override
public Category add(Category data) {
TbCategory tb = categoryRepository.save(MapstructUtils.convert(data, TbCategory.class));
data.setId(tb.getId());
return data;
}
@Override
public void deleteById(String s) {
categoryRepository.deleteById(s);

View File

@ -42,12 +42,6 @@ public class ChannelConfigDataImpl implements IChannelConfigData {
return data;
}
@Override
public ChannelConfig add(ChannelConfig data) {
data.setCreateAt(System.currentTimeMillis());
return save(data);
}
@Override
public void deleteById(String id) {
channelConfigRepository.deleteById(id);

View File

@ -44,11 +44,6 @@ public class ChannelDataImpl implements IChannelData {
return data;
}
@Override
public Channel add(Channel data) {
data.setCreateAt(System.currentTimeMillis());
return save(data);
}
@Override
public void deleteById(String id) {

View File

@ -43,11 +43,6 @@ public class ChannelTemplateDataImpl implements IChannelTemplateData {
return data;
}
@Override
public ChannelTemplate add(ChannelTemplate data) {
data.setCreateAt(System.currentTimeMillis());
return save(data);
}
@Override
public void deleteById(String id) {

View File

@ -1,69 +0,0 @@
/*
* +----------------------------------------------------------------------
* | Copyright (c) 2021-2022 All rights reserved.
* +----------------------------------------------------------------------
* | Licensed
* +----------------------------------------------------------------------
* | Author: xw2sy@163.com
* +----------------------------------------------------------------------
*/
package cc.iotkit.data.service;
import cc.iotkit.data.ICommonData;
import cc.iotkit.model.Id;
import cc.iotkit.common.api.Paging;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public class CommonService<VO extends Id<T>, T> implements ICommonData<VO, T> {
private final JpaRepository<VO, T> repository;
public CommonService(JpaRepository<VO, T> repository) {
this.repository = repository;
}
@Override
public VO findById(T id) {
return repository.findById(id).orElse(null);
}
@Override
public VO save(VO data) {
return repository.save(data);
}
@Override
public VO add(VO data) {
return repository.save(data);
}
@Override
public void deleteById(T id) {
repository.deleteById(id);
}
@Override
public void deleteByIds(T[] ts) {
}
@Override
public long count() {
return repository.count();
}
@Override
public List<VO> findAll() {
return repository.findAll();
}
@Override
public Paging<VO> findAll(int page, int size) {
Page<VO> rst = repository.findAll(Pageable.ofSize(size).withPage(page - 1));
return new Paging<>(rst.getTotalElements(), rst.getContent());
}
}

View File

@ -56,10 +56,6 @@ public class DeviceConfigDataImpl implements IDeviceConfigData {
return data;
}
@Override
public DeviceConfig add(DeviceConfig data) {
return save(data);
}
@Override
public void deleteById(String s) {

View File

@ -45,11 +45,6 @@ public class DeviceGroupDataImpl implements IDeviceGroupData {
return data;
}
@Override
public DeviceGroup add(DeviceGroup data) {
data.setCreateAt(System.currentTimeMillis());
return save(data);
}
@Override
public void deleteById(String s) {

View File

@ -463,12 +463,6 @@ public class DeviceInfoDataImpl implements IDeviceInfoData {
return data;
}
@Override
public DeviceInfo add(DeviceInfo data) {
data.setCreateAt(System.currentTimeMillis());
return save(data);
}
@Override
public void deleteById(String s) {
deviceInfoRepository.deleteById(s);

View File

@ -60,10 +60,6 @@ public class HomeDataImpl implements IHomeData {
return data;
}
@Override
public Home add(Home data) {
return save(data);
}
@Override
public void deleteById(String s) {

View File

@ -51,11 +51,6 @@ public class OauthClientDataImpl implements IOauthClientData {
return data;
}
@Override
public OauthClient add(OauthClient data) {
return save(data);
}
@Override
public void deleteById(String s) {
oauthClientRepository.deleteById(s);

View File

@ -56,11 +56,6 @@ public class ProductDataImpl implements IProductData {
return data;
}
@Override
public Product add(Product data) {
data.setCreateAt(System.currentTimeMillis());
return save(data);
}
@Override
public void deleteById(String s) {

View File

@ -47,10 +47,6 @@ public class ProductModelDataImpl implements IProductModelData {
return null;
}
@Override
public ProductModel add(ProductModel data) {
return save(data);
}
@Override
public void deleteById(String s) {

View File

@ -66,10 +66,6 @@ public class ProtocolComponentDataImpl implements IProtocolComponentData {
return data;
}
@Override
public ProtocolComponent add(ProtocolComponent data) {
return save(data);
}
@Override
public void deleteById(String s) {

View File

@ -66,10 +66,6 @@ public class ProtocolConverterDataImpl implements IProtocolConverterData {
return data;
}
@Override
public ProtocolConverter add(ProtocolConverter data) {
return save(data);
}
@Override
public void deleteById(String s) {

View File

@ -86,11 +86,6 @@ public class RuleInfoDataImpl implements IRuleInfoData {
return data;
}
@Override
public RuleInfo add(RuleInfo data) {
return save(data);
}
@Override
public void deleteById(String s) {
ruleInfoRepository.deleteById(s);

View File

@ -70,11 +70,6 @@ public class SpaceDataImpl implements ISpaceData {
return data;
}
@Override
public Space add(Space data) {
return save(data);
}
@Override
public void deleteById(String s) {
spaceRepository.deleteById(s);

View File

@ -95,11 +95,6 @@ public class SpaceDeviceDataImpl implements ISpaceDeviceData {
return data;
}
@Override
public SpaceDevice add(SpaceDevice data) {
return save(data);
}
@Override
public void deleteById(String s) {
spaceDeviceRepository.deleteById(s);

View File

@ -1,15 +1,31 @@
package cc.iotkit.data.service;
import static cc.iotkit.data.model.QTbSysConfig.tbSysConfig;
import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.enums.ErrCode;
import cc.iotkit.common.exception.BizException;
import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.common.utils.StringUtils;
import cc.iotkit.data.dao.SysConfigRepository;
import cc.iotkit.data.model.TbSysConfig;
import cc.iotkit.data.system.ISysConfigData;
import cc.iotkit.common.api.Paging;
import cc.iotkit.data.util.PageBuilder;
import cc.iotkit.data.util.PredicateBuilder;
import cc.iotkit.model.system.SysConfig;
import cn.hutool.core.collection.CollUtil;
import com.querydsl.core.types.Predicate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;
@Primary
@ -22,7 +38,8 @@ public class SysConfigDataImpl implements ISysConfigData {
@Override
public SysConfig findById(Long id) {
TbSysConfig tbSysConfig = alertConfigRepository.findById(id).orElseThrow();
TbSysConfig tbSysConfig = alertConfigRepository.findById(id).orElseThrow(() ->
new BizException(ErrCode.DATA_NOT_EXIST));
return MapstructUtils.convert(tbSysConfig,SysConfig.class);
}
@ -33,43 +50,67 @@ public class SysConfigDataImpl implements ISysConfigData {
}
@Override
public SysConfig add(SysConfig data) {
return null;
public List<SysConfig> findByIds(Collection<Long> id) {
throw new BizException(ErrCode.UNSUPPORTED_OPERATION_EXCEPTION);
}
@Override
public void deleteById(Long id) {
public void batchSave(List<SysConfig> data) {
throw new BizException(ErrCode.UNSUPPORTED_OPERATION_EXCEPTION);
}
@Override
public void deleteByIds(Long[] longs) {
public void deleteById(Long aLong) {
throw new BizException(ErrCode.UNSUPPORTED_OPERATION_EXCEPTION);
}
@Override
public void deleteByIds(Collection<Long> longs) {
throw new BizException(ErrCode.UNSUPPORTED_OPERATION_EXCEPTION);
}
@Override
public long count() {
return 0;
throw new BizException(ErrCode.UNSUPPORTED_OPERATION_EXCEPTION);
}
@Override
public List<SysConfig> findAll() {
return null;
throw new BizException(ErrCode.UNSUPPORTED_OPERATION_EXCEPTION);
}
@Override
public Paging<SysConfig> findAll(int page, int size) {
return null;
}
public Paging<SysConfig> findAll(PageRequest<SysConfig> pageRequest) {
SysConfig query = pageRequest.getData();
Predicate predicate = PredicateBuilder.instance(tbSysConfig.configId.isNotNull())
.and(StringUtils.isNotEmpty(query.getConfigKey()),() -> tbSysConfig.configKey.eq(query.getConfigKey()))
.build();
List<Order> orders = new ArrayList<>();
Map<String,String> sortMap = pageRequest.getSortMap();
if (CollUtil.isNotEmpty(sortMap)){
sortMap.forEach((k,v) -> {
orders.add(new Order(Direction.ASC, k));
});
}
// TODO: 2023/5/26 抽成通用工具类方法
@Override
public Paging<SysConfig> findConfigs(SysConfig query) {
return null;
alertConfigRepository.findAll(predicate,PageBuilder.toPageable(pageRequest, Sort.by(orders)));
throw new BizException(ErrCode.UNSUPPORTED_OPERATION_EXCEPTION);
}
@Override
public SysConfig findByConfigKey(String configKey) {
return null;
public List<SysConfig> findAllByCondition(SysConfig data) {
throw new BizException(ErrCode.UNSUPPORTED_OPERATION_EXCEPTION);
}
@Override
public SysConfig findOneByCondition(SysConfig data) {
throw new BizException(ErrCode.UNSUPPORTED_OPERATION_EXCEPTION);
}
}

View File

@ -65,11 +65,6 @@ public class TaskInfoDataImpl implements ITaskInfoData {
return data;
}
@Override
public TaskInfo add(TaskInfo data) {
return save(data);
}
@Override
public void deleteById(String s) {
taskInfoRepository.deleteById(s);

View File

@ -43,11 +43,6 @@ public class ThingModelDataImpl implements IThingModelData {
return data;
}
@Override
public ThingModel add(ThingModel data) {
return save(data);
}
@Override
public void deleteById(String s) {
thingModelRepository.deleteById(s);

View File

@ -62,11 +62,6 @@ public class UserInfoDataImpl implements IUserInfoData {
return data;
}
@Override
public UserInfo add(UserInfo data) {
return save(data);
}
@Override
public void deleteById(String s) {
userInfoRepository.deleteById(s);

View File

@ -105,11 +105,6 @@ public class VirtualDeviceDataImpl implements IVirtualDeviceData {
return data;
}
@Override
public VirtualDevice add(VirtualDevice data) {
return save(data);
}
@Override
@Transactional
public void deleteById(String s) {

View File

@ -0,0 +1,37 @@
package cc.iotkit.data.util;
import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.PageRequestEmpty;
import cc.iotkit.model.system.SysConfig;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
/**
* @author: Longjun.Tu
* @description:
* @date:created in 2023/5/26 17:14
* @modificed by:
*/
public class PageBuilder {
public static Pageable toPageable(PageRequest<?> request, Sort.Direction direction, String... properties) {
return (Pageable)(request.getPageSize() <= 0 ? Pageable.unpaged() : org.springframework.data.domain.PageRequest.of(request.getPageNum() - 1, request.getPageSize(), direction, properties));
}
public static Pageable toPageable(PageRequest<?> request) {
return (Pageable)(request.getPageSize() <= 0 ? Pageable.unpaged() : org.springframework.data.domain.PageRequest.of(request.getPageNum() - 1, request.getPageSize()));
}
public static Pageable toPageable(PageRequestEmpty request) {
return (Pageable)(request.getPageNum() <= 0 ? Pageable.unpaged() : org.springframework.data.domain.PageRequest.of(request.getPageNum() - 1, request.getPageSize()));
}
public static Pageable toPageable(PageRequestEmpty request, Sort.Direction direction, String... properties) {
return (Pageable)(request.getPageNum() <= 0 ? Pageable.unpaged() : org.springframework.data.domain.PageRequest.of(request.getPageNum() - 1, request.getPageSize(), direction, properties));
}
public static Pageable toPageable(PageRequest<?> request, Sort sort) {
return (Pageable)(request.getPageSize() <= 0 ? Pageable.unpaged() : org.springframework.data.domain.PageRequest.of(request.getPageNum() - 1, request.getPageSize(), sort));
}
}

View File

@ -0,0 +1,116 @@
package cc.iotkit.data.util;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.Expressions;
import java.util.function.Supplier;
/**
* @author: Longjun.Tu
* @description:
* @date:created in 2023/5/26 17:02
* @modificed by:
*/
public class PredicateBuilder {
/**
* 1 = 1, .
*/
private static final BooleanExpression ALWAYS_TRUE = Expressions.ONE.eq(Expressions.ONE);
private BooleanExpression expression;
private PredicateBuilder(BooleanExpression expression) {
this.expression = expression;
}
/**
* {@link PredicateBuilder}.
*
* @return PredicateBuilder
*/
public static PredicateBuilder instance() {
return instance(null);
}
/**
* {@link PredicateBuilder}.
*
* @param init
* @return PredicateBuilder
*/
public static PredicateBuilder instance(BooleanExpression init) {
return new PredicateBuilder(init);
}
/**
* 使 'and'
*
* @param expr Boolean expressions
* @return PredicateBuilder
*/
public PredicateBuilder and(BooleanExpression expr) {
return and(true, () -> expr);
}
/**
* true, 使 'and'
*
* @param condition , false, .
* @param exprSupplier expression supplier.
* @return PredicateBuilder
*/
public PredicateBuilder and(boolean condition, Supplier<BooleanExpression> exprSupplier) {
if (condition) {
if (exprIsNull()) {
expression = exprSupplier.get();
return this;
}
expression = expression.and(exprSupplier.get());
}
return this;
}
/**
* 使 'or'
*
* @param expr Boolean expressions
* @return PredicateBuilder
*/
public PredicateBuilder or(BooleanExpression expr) {
return or(true, () -> expr);
}
/**
* true, 使 'or'
*
* @param condition , false, .
* @param exprSupplier expression supplier.
* @return PredicateBuilder
*/
public PredicateBuilder or(boolean condition, Supplier<BooleanExpression> exprSupplier) {
if (condition) {
if (exprIsNull()) {
expression = exprSupplier.get();
return this;
}
expression = expression.or(exprSupplier.get());
}
return this;
}
/**
* {@link BooleanExpression}
*
* @return Predicate, , 1 = 1.
*/
public Predicate build() {
if (exprIsNull()) {
return ALWAYS_TRUE;
}
return expression;
}
private boolean exprIsNull() {
return null == expression;
}
}

View File

@ -1,138 +1,96 @@
//package cc.iotkit.common.tenant.helper;
//
//import cc.iotkit.common.constant.GlobalConstants;
//import cc.iotkit.common.redis.utils.RedisUtils;
//import cc.iotkit.common.satoken.utils.LoginHelper;
//import cc.iotkit.common.utils.SpringUtils;
//import cc.iotkit.common.utils.StringUtils;
//import cn.dev33.satoken.context.SaHolder;
//import cn.dev33.satoken.spring.SpringMVCUtil;
//import cn.hutool.core.convert.Convert;
//import com.alibaba.ttl.TransmittableThreadLocal;
//import lombok.AccessLevel;
//import lombok.NoArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//
//import java.util.function.Supplier;
//
///**
// * 租户助手
// *
// * @author Lion Li
// */
//@Slf4j
//@NoArgsConstructor(access = AccessLevel.PRIVATE)
//public class TenantHelper {
//
// private static final String DYNAMIC_TENANT_KEY = GlobalConstants.GLOBAL_REDIS_KEY + "dynamicTenant";
//
// private static final ThreadLocal<String> TEMP_DYNAMIC_TENANT = new TransmittableThreadLocal<>();
//
// /**
// * 租户功能是否启用
// */
// public static boolean isEnable() {
// return Convert.toBool(SpringUtils.getProperty("tenant.enable"), false);
// }
//
// /**
// * 开启忽略租户(开启后需手动调用 {@link #disableIgnore()} 关闭)
// */
// public static void enableIgnore() {
// InterceptorIgnoreHelper.handle(IgnoreStrategy.builder().tenantLine(true).build());
// }
//
// /**
// * 关闭忽略租户
// */
// public static void disableIgnore() {
// InterceptorIgnoreHelper.clearIgnoreStrategy();
// }
//
// /**
// * 在忽略租户中执行
// *
// * @param handle 处理执行方法
// */
// public static void ignore(Runnable handle) {
// enableIgnore();
// try {
// handle.run();
// } finally {
// disableIgnore();
// }
// }
//
// /**
// * 在忽略租户中执行
// *
// * @param handle 处理执行方法
// */
// public static <T> T ignore(Supplier<T> handle) {
// enableIgnore();
// try {
// return handle.get();
// } finally {
// disableIgnore();
// }
// }
//
// /**
// * 设置动态租户(一直有效 需要手动清理)
// * <p>
// * 如果为非web环境 那么只在当前线程内生效
// */
// public static void setDynamic(String tenantId) {
// if (!SpringMVCUtil.isWeb()) {
// TEMP_DYNAMIC_TENANT.set(tenantId);
// return;
// }
// String cacheKey = DYNAMIC_TENANT_KEY + ":" + LoginHelper.getUserId();
// RedisUtils.setCacheObject(cacheKey, tenantId);
// SaHolder.getStorage().set(cacheKey, tenantId);
// }
//
// /**
// * 获取动态租户(一直有效 需要手动清理)
// * <p>
// * 如果为非web环境 那么只在当前线程内生效
// */
// public static String getDynamic() {
// if (!SpringMVCUtil.isWeb()) {
// return TEMP_DYNAMIC_TENANT.get();
// }
// String cacheKey = DYNAMIC_TENANT_KEY + ":" + LoginHelper.getUserId();
// String tenantId = (String) SaHolder.getStorage().get(cacheKey);
// if (StringUtils.isNotBlank(tenantId)) {
// return tenantId;
// }
// tenantId = RedisUtils.getCacheObject(cacheKey);
// SaHolder.getStorage().set(cacheKey, tenantId);
// return tenantId;
// }
//
// /**
// * 清除动态租户
// */
// public static void clearDynamic() {
// if (!SpringMVCUtil.isWeb()) {
// TEMP_DYNAMIC_TENANT.remove();
// return;
// }
// String cacheKey = DYNAMIC_TENANT_KEY + ":" + LoginHelper.getUserId();
// RedisUtils.deleteObject(cacheKey);
// SaHolder.getStorage().delete(cacheKey);
// }
//
// /**
// * 获取当前租户id(动态租户优先)
// */
// public static String getTenantId() {
// String tenantId = TenantHelper.getDynamic();
// if (StringUtils.isBlank(tenantId)) {
// tenantId = LoginHelper.getTenantId();
// }
// return tenantId;
// }
//
//}
package cc.iotkit.common.tenant.helper;
import cc.iotkit.common.constant.GlobalConstants;
import cc.iotkit.common.redis.utils.RedisUtils;
import cc.iotkit.common.satoken.utils.LoginHelper;
import cc.iotkit.common.utils.SpringUtils;
import cc.iotkit.common.utils.StringUtils;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.spring.SpringMVCUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.function.Supplier;
/**
*
*
* @author Lion Li
*/
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TenantHelper {
private static final String DYNAMIC_TENANT_KEY = GlobalConstants.GLOBAL_REDIS_KEY + "dynamicTenant";
private static final ThreadLocal<String> TEMP_DYNAMIC_TENANT = new TransmittableThreadLocal<>();
/**
*
*/
public static boolean isEnable() {
return Convert.toBool(SpringUtils.getProperty("tenant.enable"), false);
}
/**
* ( )
* <p>
* web 线
*/
public static void setDynamic(String tenantId) {
if (!SpringMVCUtil.isWeb()) {
TEMP_DYNAMIC_TENANT.set(tenantId);
return;
}
String cacheKey = DYNAMIC_TENANT_KEY + ":" + LoginHelper.getUserId();
RedisUtils.setCacheObject(cacheKey, tenantId);
SaHolder.getStorage().set(cacheKey, tenantId);
}
/**
* ( )
* <p>
* web 线
*/
public static String getDynamic() {
if (!SpringMVCUtil.isWeb()) {
return TEMP_DYNAMIC_TENANT.get();
}
String cacheKey = DYNAMIC_TENANT_KEY + ":" + LoginHelper.getUserId();
String tenantId = (String) SaHolder.getStorage().get(cacheKey);
if (StringUtils.isNotBlank(tenantId)) {
return tenantId;
}
tenantId = RedisUtils.getCacheObject(cacheKey);
SaHolder.getStorage().set(cacheKey, tenantId);
return tenantId;
}
/**
*
*/
public static void clearDynamic() {
if (!SpringMVCUtil.isWeb()) {
TEMP_DYNAMIC_TENANT.remove();
return;
}
String cacheKey = DYNAMIC_TENANT_KEY + ":" + LoginHelper.getUserId();
RedisUtils.deleteObject(cacheKey);
SaHolder.getStorage().delete(cacheKey);
}
/**
* id()
*/
public static String getTenantId() {
String tenantId = TenantHelper.getDynamic();
if (StringUtils.isBlank(tenantId)) {
tenantId = LoginHelper.getTenantId();
}
return tenantId;
}
}

View File

@ -53,6 +53,17 @@
<artifactId>iot-data-serviceImpl-rdb</artifactId>
</dependency>
<dependency>
<groupId>cc.iotkit</groupId>
<artifactId>iot-common-doc</artifactId>
</dependency>
<dependency>
<groupId>cc.iotkit</groupId>
<artifactId>iot-common-oss</artifactId>
</dependency>
</dependencies>
<build>

View File

@ -2,14 +2,19 @@ package cc.iotkit.system.controller;
import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.api.Request;
import cc.iotkit.common.log.annotation.Log;
import cc.iotkit.common.log.enums.BusinessType;
import cc.iotkit.common.excel.utils.ExcelUtil;
import cc.iotkit.common.validate.EditGroup;
import cc.iotkit.common.validate.QueryGroup;
import cc.iotkit.common.web.core.BaseController;
import cc.iotkit.system.dto.bo.SysConfigBo;
import cc.iotkit.system.dto.vo.SysConfigVo;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cc.iotkit.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@ -26,106 +31,89 @@ import java.util.List;
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/config")
@Api(tags = "参数配置 信息操作处理")
public class SysConfigController extends BaseController {
private final ISysConfigService configService;
private final ISysConfigService configService;
/**
*
*/
@SaCheckPermission("system:config:list")
@PostMapping("/list")
public Paging<SysConfigVo> list(@RequestBody @Validated PageRequest<SysConfigBo> query) {
return configService.selectPageConfigList(query);
}
/**
*
*/
@Log(title = "参数管理", businessType = BusinessType.EXPORT)
@SaCheckPermission("system:config:export")
@PostMapping("/export")
public void export(SysConfigBo config, HttpServletResponse response) {
List<SysConfigVo> list = configService.selectConfigList(config);
ExcelUtil.exportExcel(list, "参数数据", SysConfigVo.class, response);
}
@ApiOperation("获取参数配置列表")
@SaCheckPermission("system:config:list")
@PostMapping("/list")
public Paging<SysConfigVo> list(
@RequestBody @Validated(QueryGroup.class) PageRequest<SysConfigBo> query) {
return configService.selectPageConfigList(query);
}
/**
*
*
* @param configId ID
*/
@SaCheckPermission("system:config:query")
@GetMapping(value = "/{configId}")
public SysConfigVo getInfo(@PathVariable Long configId) {
return configService.selectConfigById(configId);
}
@ApiOperation("导出参数配置列表")
@Log(title = "参数管理", businessType = BusinessType.EXPORT)
@SaCheckPermission("system:config:export")
@PostMapping("/export")
public void export(@RequestBody @Validated(QueryGroup.class) SysConfigBo config,
HttpServletResponse response) {
List<SysConfigVo> list = configService.selectConfigList(config);
ExcelUtil.exportExcel(list, "参数数据", SysConfigVo.class, response);
}
/**
*
*
* @param configKey Key
*/
@GetMapping(value = "/configKey/{configKey}")
public void getConfigKey(@PathVariable String configKey) {
configService.selectConfigByKey(configKey);
}
/**
*
*/
@SaCheckPermission("system:config:add")
@Log(title = "参数管理", businessType = BusinessType.INSERT)
@PostMapping
public void add(@Validated @RequestBody SysConfigBo config) {
if (!configService.checkConfigKeyUnique(config)) {
fail("新增参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
configService.insertConfig(config);
}
@ApiOperation("根据参数编号获取详细信息")
@SaCheckPermission("system:config:query")
@PostMapping(value = "/getInfo")
public SysConfigVo getInfo(@RequestBody @Validated Request<Long> request) {
return configService.selectConfigById(request.getData());
}
/**
*
*/
@SaCheckPermission("system:config:edit")
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
@PutMapping
public void edit(@Validated @RequestBody SysConfigBo config) {
if (!configService.checkConfigKeyUnique(config)) {
fail("修改参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
configService.updateConfig(config);
}
/**
*
*/
@SaCheckPermission("system:config:edit")
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
@PutMapping("/updateByKey")
public void updateByKey(@RequestBody SysConfigBo config) {
configService.updateConfig(config);
}
@ApiOperation("根据参数键名查询参数值")
@PostMapping(value = "/getConfigKey")
public void getConfigKey(@RequestBody @Validated Request<String> request) {
configService.selectConfigByKey(request.getData());
}
/**
*
*
* @param configIds ID
*/
@SaCheckPermission("system:config:remove")
@Log(title = "参数管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{configIds}")
public void remove(@PathVariable Long[] configIds) {
configService.deleteConfigByIds(configIds);
}
/**
*
*/
@SaCheckPermission("system:config:remove")
@Log(title = "参数管理", businessType = BusinessType.CLEAN)
@DeleteMapping("/refreshCache")
public void refreshCache() {
configService.resetConfigCache();
@ApiOperation("新增参数配置")
@SaCheckPermission("system:config:add")
@Log(title = "参数管理", businessType = BusinessType.INSERT)
@PostMapping(value = "/add")
public void add(@RequestBody @Validated(EditGroup.class) Request<SysConfigBo> request) {
if (!configService.checkConfigKeyUnique(request.getData())) {
fail("新增参数'" + request.getData().getConfigName() + "'失败,参数键名已存在");
}
configService.insertConfig(request.getData());
}
@ApiOperation("修改参数配置")
@SaCheckPermission("system:config:edit")
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
@PostMapping(value = "/edit")
public void edit(@RequestBody @Validated(EditGroup.class) Request<SysConfigBo> request) {
if (!configService.checkConfigKeyUnique(request.getData())) {
fail("修改参数'" + request.getData().getConfigName() + "'失败,参数键名已存在");
}
configService.updateConfig(request.getData());
}
@ApiOperation("根据参数键名修改参数配置")
@SaCheckPermission("system:config:edit")
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
@PostMapping("/updateByKey")
public void updateByKey(@RequestBody @Validated(EditGroup.class) Request<SysConfigBo> request) {
configService.updateConfig(request.getData());
}
@ApiOperation("删除参数配置")
@SaCheckPermission("system:config:remove")
@Log(title = "参数管理", businessType = BusinessType.DELETE)
@PostMapping("/remove")
public void remove(@RequestBody @Validated Request<List<Long>> request) {
configService.deleteConfigByIds(request.getData());
}
@ApiOperation("刷新参数缓存")
@SaCheckPermission("system:config:remove")
@Log(title = "参数管理", businessType = BusinessType.CLEAN)
@PostMapping("/refreshCache")
public void refreshCache() {
configService.resetConfigCache();
}
}

View File

@ -6,6 +6,7 @@ import cc.iotkit.common.api.Paging;
import cc.iotkit.common.excel.utils.ExcelUtil;
import cc.iotkit.common.log.annotation.Log;
import cc.iotkit.common.log.enums.BusinessType;
import cc.iotkit.common.tenant.helper.TenantHelper;
import cc.iotkit.common.validate.AddGroup;
import cc.iotkit.common.validate.EditGroup;
import cc.iotkit.common.web.core.BaseController;
@ -92,7 +93,7 @@ public class SysTenantController extends BaseController {
if (!tenantService.checkCompanyNameUnique(bo)) {
fail("新增租户'" + bo.getCompanyName() + "'失败,企业名称已存在");
}
TenantHelper.ignore(() -> tenantService.insertByBo(bo));
//TenantHelper.ignore(() -> tenantService.insertByBo(bo));
}
/**
@ -168,7 +169,7 @@ public class SysTenantController extends BaseController {
@Log(title = "租户", businessType = BusinessType.UPDATE)
@GetMapping("/syncTenantPackage")
public void syncTenantPackage(@NotBlank(message = "租户ID不能为空") String tenantId, @NotBlank(message = "套餐ID不能为空") String packageId) {
TenantHelper.ignore(() -> tenantService.syncTenantPackage(tenantId, packageId));
//TenantHelper.ignore(() -> tenantService.syncTenantPackage(tenantId, packageId));
}
}

View File

@ -69,7 +69,7 @@ public interface ISysConfigService {
*
* @param configIds ID
*/
void deleteConfigByIds(Long[] configIds);
void deleteConfigByIds(List<Long> configIds);
/**
*

View File

@ -1,8 +1,8 @@
package cc.iotkit.system.service.impl;
import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.constant.CacheNames;
import cc.iotkit.common.constant.UserConstants;
import cc.iotkit.common.exception.BizException;
import cc.iotkit.common.redis.utils.CacheUtils;
@ -14,16 +14,13 @@ import cc.iotkit.data.system.ISysConfigData;
import cc.iotkit.model.system.SysConfig;
import cc.iotkit.system.dto.bo.SysConfigBo;
import cc.iotkit.system.dto.vo.SysConfigVo;
import cn.hutool.core.util.ObjectUtil;
import cc.iotkit.system.service.ISysConfigService;
import cn.hutool.core.util.ObjectUtil;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cc.iotkit.common.api.Paging;
import java.util.ArrayList;
import java.util.List;
/**
*
@ -39,8 +36,8 @@ public class SysConfigServiceImpl implements ISysConfigService, ConfigService {
@Override
public Paging<SysConfigVo> selectPageConfigList(PageRequest<SysConfigBo> query) {
SysConfig sysConfig = MapstructUtils.convert(query.getData(), SysConfig.class);
return MapstructUtils.convert(sysConfigData.findConfigs(sysConfig), SysConfigVo.class);
PageRequest<SysConfig> pageRequest = PageRequest.copyPageRequest(query,MapstructUtils.convert(query.getData(), SysConfig.class));
return MapstructUtils.convert(sysConfigData.findAll(pageRequest), SysConfigVo.class);
}
/**
@ -62,7 +59,9 @@ public class SysConfigServiceImpl implements ISysConfigService, ConfigService {
*/
@Override
public String selectConfigByKey(String configKey) {
SysConfig sysConfig = sysConfigData.findByConfigKey(configKey);
SysConfig data = new SysConfig();
data.setConfigKey(configKey);
SysConfig sysConfig = sysConfigData.findOneByCondition(data);
if (ObjectUtil.isNotNull(sysConfig)) {
return sysConfig.getConfigValue();
}
@ -171,13 +170,13 @@ public class SysConfigServiceImpl implements ISysConfigService, ConfigService {
* @param configIds ID
*/
@Override
public void deleteConfigByIds(Long[] configIds) {
public void deleteConfigByIds(List<Long> configIds) {
for (Long configId : configIds) {
SysConfig old = sysConfigData.findById(configId);
if (StringUtils.equals(UserConstants.YES, old.getConfigType())) {
throw new BizException(String.format("内置参数【%1$s】不能删除 ", old.getConfigKey()));
}
// CacheUtils.evict(CacheNames.SYS_CONFIG, config.getConfigKey());
CacheUtils.evict(CacheNames.SYS_CONFIG, old.getConfigKey());
}
sysConfigData.deleteByIds(configIds);
}

View File

@ -4,7 +4,12 @@ import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.constant.CacheNames;
import cc.iotkit.common.exception.BizException;
import cc.iotkit.common.oss.core.OssClient;
import cc.iotkit.common.oss.entity.UploadResult;
import cc.iotkit.common.oss.enumd.AccessPolicyType;
import cc.iotkit.common.oss.factory.OssFactory;
import cc.iotkit.common.service.OssService;
import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.common.utils.SpringUtils;
import cc.iotkit.common.utils.StreamUtils;
import cc.iotkit.common.utils.StringUtils;

View File

@ -335,6 +335,12 @@
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>cc.iotkit</groupId>
<artifactId>iot-common-oss</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>cc.iotkit</groupId>
<artifactId>iot-common-excel</artifactId>