0

I want to set values from an dto object and insert them in database with save jpa repository methode can i insert a default value if attributes is not valid(null or size is to longer) using jpa ?

dto object :

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

I use a validator to control values :

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();
        }
Anass EL
  • 1
  • 2
  • How are you planning to throw an exception if the input is invalid.? – Sreyas Sep 06 '21 at 08:04
  • 1
    it better that database handle the default value so when you create table make that column has default value and based on your validation you do not provide a value of it –  Sep 06 '21 at 08:11
  • @Sreyas if violations.size() is is greater than 0 i don't insert in database – Anass EL Sep 06 '21 at 08:28
  • @justsomeone i specified a default value in database when i created the table but how can i ignore not valid attributes and insert the default value ? – Anass EL Sep 06 '21 at 08:33
  • @AnassEL check both of those links https://stackoverflow.com/questions/1281952/what-is-the-easiest-way-to-ignore-a-jpa-field-during-persistence https://www.baeldung.com/jpa-transient-ignore-field –  Sep 06 '21 at 08:38

1 Answers1

0

i did a basic method to verify attributes values for example :

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

I check it by this method :

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