gpt4 book ai didi

java - 内部包含具有不同组接口(interface)的 bean 的多个 bean 验证

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:15:21 26 4
gpt4 key购买 nike

我在验证一个非常具体的 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;
}
}

如您所见,我这里有两个地址字段 - 一个用于送货地址,另一个用于发票地址。
每种地址的验证应该不同,例如我不需要送货地址中的增值税号,但我可能需要发票中的增值税号。

我使用组对发票地址和送货地址执行不同的验证,如果我对地址字段进行手动验证,它就可以正常工作。

但现在我想用地址(如果可用)验证整个客户对象。
我试着用下面的代码来做到这一点:

    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 接口(interface)收到送货地址错误,从 ShippingAddressCheck 收到发票地址错误。

这里是 Addresses bean 的简短声明:

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


有什么方法可以运行验证,以便使用 InvoiceAddressCheck 组验证 invoiceAddress 并使用 ShippingAddressCheck 组验证 shippingAddress,但在验证 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;
}

这不是很好的解决方案,但它可以满足我的需要。如果您找到更好的解决方案,请告诉我:)

关于java - 内部包含具有不同组接口(interface)的 bean 的多个 bean 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7676065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com