【问题标题】:How can i insert default value in database if attributes is not valid with JPA如果属性对 JPA 无效,我如何在数据库中插入默认值
【发布时间】:2022-01-16 04:56:40
【问题描述】:

我想从 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();
        }

【问题讨论】:

  • 如果输入无效,你打算如何抛出异常?
  • 最好让数据库处理默认值,以便在创建表时使该列具有默认值,并且根据您的验证,您不提供它的值
  • @Sreyas 如果 violation.size() 大于 0 我不插入数据库
  • @justsomeone 我在创建表时在数据库中指定了一个默认值,但是如何忽略无效属性并插入默认值?

标签: java spring-boot validation jpa hibernate-validator


【解决方案1】:

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

 @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;
    }

【讨论】:

    猜你喜欢
    • 2019-05-02
    • 2011-07-23
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    • 2016-09-10
    • 2012-02-06
    相关资源
    最近更新 更多