引言

数据库小技能

I 字段前处理:检测

@JsonFormat注解:主要是后台到前台的时间格式的转换

@DataFormat注解:主要是前后到后台的时间格式的转换

@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date blog_date;// 博客发布日期

1.1 格式校验

多个代理商编号时,请用英文逗号,分隔

try {
            facilitatorIds4input= Arrays.asList(input.getFacilitatorIds().split(","))
                    .stream().map(s -> Long.parseLong(s)).collect(Collectors.toList());
        } catch (Exception e) {
            throw CommonException.create(ServerResponse.createByError("代理商id,多个代理商编号时,请用英文逗号,分隔"));
        }

使用注解进行格式校验

public class ApiPubSigPayRequest extends ApiBaseRequest{
    @NotBlank(message = "订单日期不能为空")
    @Pattern(regexp = "(^[0-9]*$)",message = "订单日期格式有误")
    private String orderDate;//订单日期 yyyyMMddHHmmss

    @DecimalMin(value = "1" , message = "订单金额必须大于1分")
    private Long payAmt;//订单金额 分

    @DecimalMin(value = "1" , message = "订单金额必须大于1分")
    private Long totAmt;//总金额 分

    @NotBlank(message = "交易码不能为空")
    private String transCode;//交易码

    @NotBlank(message = "微信/支付宝小程序appId不能为空")
    private String subAppid;

    @NotBlank(message = "微信/支付宝用户id不能为空")
    private String subOpenid;

    private String subject;//订单标题

}

1.2 检测唯一性

如果唯一性的其中一个字段时可选的,统一保存""空串,便于比较。

if(position.getEquipmentSn() ==null){// 统一保存""空串,便于比较
            position.setEquipmentSn("");
        }
        if (!(position.getMerchantId().equals(input.getMerchantId()) && position.getEquipmentSn().equals(input.getEquipmentSn()))) {
            // 检测唯一性
            if (getPosition(input.getMerchantId(), input.getEquipmentSn()) != null) {
                throw CommonException.create(ServerResponse.createByError("规则已经存在"));
            }
        }

1.3 日期范围查询

请求参数LocalDate

@ApiModelProperty(value = "开始时间")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate startTime;

    @ApiModelProperty(value = "结束时间")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate endTime;

LocalDate 转LocalDateTime

if (input.getStartTime() != null) {
            lambda.apply("create_time > {0}",input.getStartTime().atStartOfDay());
        }
        if (input.getEndTime() != null) {
            lambda.apply("create_time < {0}",input.getEndTime().plusDays(1).atStartOfDay());
        }

II 字段后处理

2.1 List转换成用逗号分割的字符串

String exidsStr = exFacilitator.stream().map(i->i.getFacilitatorId().toString()).collect(Collectors.joining(","));

2.2 按照枚举分组数据

List<RiskFacilitatorNetLimitRateDto> rates = new ArrayList<>();
        // 按照结算周期枚举分组
        List<ESettlementCycle> cycles = Arrays.asList(ESettlementCycle.class.getEnumConstants());
        cycles.forEach(item -> {
            RiskFacilitatorNetLimitRateDto dto = new RiskFacilitatorNetLimitRateDto();
            dto.setSettlementCycle(item);
            dto.setRateList(rateList.stream().filter(i -> i.getSettlementCycle() == item).collect(Collectors.toList()));
            rates.add(dto);
        });
        return rates;

III BigDecimal处理

3.1 BigDecimal与0比较大小

如果0表示不限制 ,推微信总上限。

if(activity.getMaxAmountByDay().compareTo(BigDecimal.ZERO)==0){//BigDecimal与0比较大小 -1 小于0,1 大于0
            stockUseRule.setMaxAmountByDay(stockUseRule.getMaxAmount());
        }else{
            stockUseRule.setMaxAmountByDay(activity.getMaxAmountByDay().multiply(new BigDecimal(100)).longValue());
        }

3.2 BigDecimal 元转分

stockUseRule.setMaxAmount((activity.getMaxAmount().multiply(new BigDecimal(100)).longValue()));//乘以100(单位:分)

3.3 自定义DecimalFormat注解

新增bigDecimal格式化注解CustomDecimalFormat,默认格式#.###,可用于费率字段。

import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
//Jackson的注解继承注解
 @JacksonAnnotationsInside
// 为该注解指定一个自定义的json序列化解析器
@JsonSerialize(using = DecimalFormatSerialize.class)
public @interface CustomDecimalFormat {
    //0 整数或小数部分少位数补0
    //# 开头的0和末尾的0不显示,只要有可能就把数字拉上这个位置。
//    % 乘100然后加%
//     .小数分隔符
//     ,:整数分隔符

    String value() default "#.###";
    boolean showDecimalSeparator() default true;
    boolean zeroDisplay() default false;
}