首页 > 解决方案 > 如果属性对 JPA 无效,我如何在数据库中插入默认值

问题描述

我想从 dto 对象设置值并使用 save jpa 存储库方法将它们插入数据库中,如果属性无效(null 或大小更长),我可以使用 jpa 插入默认值吗?

dto 对象:

public class SocleList implements Serializable {

    private static final long serialVersionUID = -5008625218377596565L;
    @JsonProperty("records")
    @Valid
    private List<Socle> SocleList;
}

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString

public class Socle implements Serializable {

    private static final long serialVersionUID = -1864310486952111265L;

    @NotNull
    public int iDTechn;

    @NotNull
    @Max(value = 99999)
    private Integer code;

    @NotNull
    private String codeType;

    @NotNull
    @Size(min = 1, max = 2)
    private String red;

    private @NotNull
    @Max(value = 99999)
    Integer FPrinci;

    private @NotNull
    @Max(value = 99999)
    Integer surface;

    @NotNull
    @Size(min = 1, max = 2)
    private String Xnseigne;
}

我使用验证器来控制值:

public static int validate(SocleList SocleList,
        Validator validator) {
        Set<ConstraintViolation<SocleList>> violations;
        violations = validator.validate(socleList);

        log.info("Nombre de violations : {}", violations.size());

        for (ConstraintViolation<SocleList> constraintViolation : violations) {

        log.info("Valeur '{}' incorrecte pour '{}' : '{}' "
        , constraintViolation.getInvalidValue()
        , constraintViolation.getPropertyPath()
        , constraintViolation.getMessage());
        }
        return violations.size();
        }

标签: javaspring-bootvalidationjpahibernate-validator

解决方案


我做了一个基本的方法来验证属性值,例如:

 @JsonProperty("Code")
    @NotNull
    @Max(value = 99999)
    private Integer code;

我通过这种方法检查它:

 public void setValidCode(Integer code) {
        if (code== null || code > 99999)
            this.code= 0;
        else
            this.code= code;
    }

推荐阅读