java - 如果属性对 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();
}
解决方案
我做了一个基本的方法来验证属性值,例如:
@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;
}
推荐阅读
- php - 如何在 laravel eloquent WITH & DISTINCT 或 GROUPBY 中检索数据?
- ios - 如何在 iphone 的共享菜单中列出我的 ionic 应用程序?
- php - 控制台中的数据响应返回 HTML 代码
- node.js - 如何使用 axios/fetch (nodejs) 将 csv 文件上传到 blob 存储
- android - Android:如何创建根 CA 证书
- laravel - nginx 上的存储符号链接路径无法正常工作
- python - 如何在python中计算k个最近邻及其索引
- javascript - NodeJS 项目没有添加到对象的索引上?
- apache-camel - 使用 Apache Camel 的多播中的端点特定授权标头
- python - While循环:如何在循环期间仅设置一次(某物=整数)