我在验证一个非常特定的bean时遇到了问题。让我先给你一些代码:
@Entity
@Table(name = "customers", schema = "public", uniqueConstraints = @UniqueConstraint(columnNames = {"cus_email" }))
public class Customers extends ModelObject implements java.io.Serializable {
private static final long serialVersionUID = -3197505684643025341L;
private long cusId;
private String cusEmail;
private String cusPassword;
private Addresses shippingAddress;
private Addresses invoiceAddress;
@Id
@Column(name = "cus_id", unique = true, nullable = false)
@SequenceGenerator(name = "cus_seq", sequenceName = "customers_cus_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cus_seq")
@NotNull
public long getCusId() {
return cusId;
}
public void setCusId(long cusId) {
this.cusId = cusId;
}
@NotEmpty
@Size(min=5, max=255)
@Email
@Column(name = "cus_email", unique = true, nullable = false, length = 255)
public String getCusEmail() {
return cusEmail;
}
public void setCusEmail(String cusEmail) {
this.cusEmail = cusEmail;
}
@NotNull
@Column(name = "cus_password", nullable = false)
public String getCusPassword() {
return cusPassword;
}
public void setCusPassword(String cusPassword) {
this.cusPassword = cusPassword;
}
@NotNull
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cus_shipping_adr_id", nullable = false)
@Cascade(value = CascadeType.ALL)
@Valid
public Addresses getShippingAddress() {
return shippingAddress;
}
public void setShippingAddress(Addresses cusShippingAddress) {
this.shippingAddress = cusShippingAddress;
}
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cus_invoice_adr_id", nullable = true)
@Cascade(value = CascadeType.ALL)
@Valid
public Addresses getInvoiceAddress() {
return invoiceAddress;
}
public void setInvoiceAddress(Addresses cusInvoiceAddress) {
this.invoiceAddress = cusInvoiceAddress;
}
}
如您所见,我在这里有两个地址字段—一个用于送货地址,另一个用于发票地址。
每种类型的地址的验证应该是不同的,例如,我不需要在送货地址的增值税号码,但我可能希望在发票。
我使用组对发票地址和送货地址执行不同的验证,如果我对地址字段进行手动验证,则可以正常工作。
但是现在我想用地址(如果可用)验证整个Customer对象。
我试着用下面的代码做到这一点:
private void validateCustomerData() throws CustomerValidationException {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Customers>> constraintViolations;
constraintViolations = validator.validate(customer, Default.class, InvoiceAddressCheck.class, ShippingAddressCheck.class);
if (!constraintViolations.isEmpty()) {
throw new CustomerValidationException(3, Message.CustomerDataException, constraintViolations);
}
}
当然,这并不像它想象的那样工作,因为两个验证都在客户对象内部的地址对象的两个实例上运行,所以我从InvoiceAddressCheck接口得到送货地址错误,从ShippingAddressCheck得到发票地址错误。
@Entity
@Table(name = "addresses", schema = "public")
@TypeDef(name = "genderConverter", typeClass = GenderConverter.class)
public class Addresses extends ModelObject implements Serializable{
private static final long serialVersionUID = -1123044739678014182L;
private long adrId;
private String street;
private String houseNo;
private String zipCode;
private String state;
private String countryCode;
private String vatNo;
private Customers customersShipping;
private Customers customersInvoice;
public Addresses() {}
public Addresses(long adrId) {
super();
this.adrId = adrId;
}
@Id
@Column(name = "adr_id", unique = true, nullable = false)
@SequenceGenerator(name = "adr_seq", sequenceName = "adr_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "adr_seq")
@NotNull
public long getAdrId() {
return adrId;
}
public void setAdrId(long adrId) {
this.adrId = adrId;
}
@NotNull
@Column(name = "adr_street", nullable = false)
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
@NotEmpty(groups = ShippingAddressCheck.class)
@Column(name = "adr_house_no")
public String getHouseNo() {
return houseNo;
}
@NotEmpty(groups = ShippingAddressCheck.class)
@Column(name = "adr_zip_code")
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
@Column(name = "adr_vat_no")
@NotEmpty(groups = InvoiceAddressCheck.class)
public String getVatNo() {
return vatNo;
}
public void setVatNo(String vatNo) {
this.vatNo = vatNo;
}
@OneToOne(fetch = FetchType.LAZY, mappedBy = "shippingAddress")
public Customers getCustomersShipping() {
return customersShipping;
}
public void setCustomersShipping(Customers customersShipping) {
this.customersShipping = customersShipping;
}
@OneToOne(fetch = FetchType.LAZY, mappedBy = "invoiceAddress")
public Customers getCustomersInvoice() {
return customersInvoice;
}
public void setCustomersInvoice(Customers customersInvoice) {
this.customersInvoice = customersInvoice;
}
}
是否有任何方法可以运行验证,以便invoiceAddress使用InvoiceAddressCheck组进行验证,shippingAddress使用ShippingAddressCheck组进行验证,但在验证Customer对象期间运行?
我知道我可以为每个子主题手动操作,但这不是这里的重点。
目前的临时解决方案是为发票字段编写自定义验证,因此它只检查InvoiceAddressCheck。
下面是我的代码
注释:
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {InvoiceAddressValidator.class })
public @interface InvoiceAddressChecker {
String message() default "Invoice address incorrect.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
验证器:
public class InvoiceAddressValidator implements ConstraintValidator<InvoiceAddressChecker, Addresses> {
@Override
public void initialize(InvoiceAddressChecker params) {
}
@Override
public boolean isValid(Addresses invoiceAddress, ConstraintValidatorContext context) {
// invoice address is optional
if (invoiceAddress == null) {
return true;
}
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Addresses>> constraintViolations;
constraintViolations = validator.validate(invoiceAddress, Default.class, InvoiceAddressCheck.class);
if (constraintViolations.isEmpty()) {
return true;
} else {
context.disableDefaultConstraintViolation();
Iterator<ConstraintViolation<Addresses>> iter = constraintViolations.iterator();
while (iter.hasNext()) {
ConstraintViolation<Addresses> violation = iter.next();
context.buildConstraintViolationWithTemplate(violation.getMessage()).addNode(
violation.getPropertyPath().toString()).addConstraintViolation();
}
return false;
}
}
}
模型注释:
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cus_invoice_adr_id", nullable = true)
@Cascade(value = CascadeType.ALL)
@InvoiceAddressChecker
public Addresses getInvoiceAddress() {
return invoiceAddress;
}
这不是一个很好的解决方案,但它满足了我的需要。如果你想出更好的解决办法,请告诉我:)