Spring Boot - 如何验证嵌套的enteties

时间:2016-07-20 08:48:55

标签: java spring validation

所以我想说我有像这样的用户对象

@Entity
public class User {
    @Id
    @GeneratedValue
    private long id;
    private String name;
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "address", referencedColumnName = "id")
    private Address address;
}

@Entity
public class Address {
    @Id
    @GeneratedValue
    private long id;
    private String city;
    private String country;
}

现在我不想在实体中编写验证注释。我想要做的是在User中验证@RestController,就像这样

@RestController
public class InvoiceController {

    @RequestMapping(value="/users/add", method = RequestMethod.POST)
    public Invoice addInvoice(@Validated @RequestBody ValidUser user) {
        ... do stuff
    }
}

验证注释将在ValidUser中,就像这样。

public class ValidUser extends User {
    @NotNull
    private String name;
    @Valid
    private Address address;
}

public class ValidAddress extends Address{
    @NotNull
    private String city;
    @NotNull
    private String country;
}

当我从address中删除ValidUser字段时,验证工作正常,但在fileURL时却没有。如何使地址验证也有效?

0 个答案:

没有答案