如何在Spring中验证内部实体?

时间:2017-11-01 14:30:30

标签: spring spring-mvc

我有一个带有javax验证的Spring MVC应用程序。有没有办法验证内部实体的存在,即多对一关系而不标记内部类的id @NotNull和FK的额外长字段?

@Entity
@Table
public class MyEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    private String name;

    @ManyToOne
    @JoinColumn(name = "my_inner_entity_id")
    @NotNull
    private MyInnerEntity innerEntity;

    //@Column(name = "my_inner_entity_id") can't use it
    //@NotNull
    //private Long innerEntityId;

    //setters and getters
}

@Entity
@Table
public class MyInnerEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    //@NotNull can't use it
    private Long id;

    @NotNull
    private Integer value;

    @OneToMany(mappedBy = "innerEntity")
    private Set<MyEntity> entities = new HashSet<>();

    //setters and getters
}

@PostMapping
public MyEntity save(@RequestBody @Valid MyEntity entity) {
    //save entity
}

2 个答案:

答案 0 :(得分:0)

只需将@Valid注释添加到innerEntity属性:

@Valid
@NotNull
@ManyToOne
private MyInnerEntity innerEntity;

答案 1 :(得分:0)

通过编写自定义验证器来解决它:

@Documented
@Constraint(validatedBy = InnerIdValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface InnerId {
    String message() default "entity with id is required";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class InnerIdValidator implements ConstraintValidator<InnerId, IdObject> {

    @Override
    public boolean isValid(IdObject idObject, ConstraintValidatorContext constraintValidatorContext) {
        return idObject != null && idObject.getId() != null;
    }
}