Jakarta Bean Validation – 条件约束

huangapple go评论49阅读模式
英文:

Jakarta Bean Validation - Conditional constraint

问题

我有一组类,就像这个相当简单的例子

public class CreditTransfer {
  private String messageId;
  private Party sender;
  private Party receiver;
  private BigDecimal amount;

  // getters 和 setters
}

public class Party {
  private String name;
  private PostalAddress address;
  private Account account;

  // getters 和 setters
}

有没有一种方法可以有条件地检查 CreditTransfer 类中 sender 嵌套对象的地址是否为 null,而不必实现类级别的约束?
显然,如果我用 @Null 注解 Party 类的地址字段,它必须始终为 null,即使对于 receiver,它必须为 @NotNull。

英文:

I have a set of classes like this pretty simple example

public class CreditTransfer {
  private String messageId;
  private Party sender;
  private Party receiver;
  private BigDecimal amount;

  //getters and setters
}
public class Party {
  private String name;
  private PostalAddress address;
  private Account account;

  //getters and setters
}

Is there a way to conditionally check that address is null only for sender nested object in CreditTransfer class, without implementing a class level constraint?
Obviously if I annotate with @Null the address field of Party class it must be always null, even for receiver, where it must be @NotNull instead.

答案1

得分: 1

你可以尝试使用@ConvertGroup。对于发送者和接收者的情况,您需要两个组:

	interface AddressRequired {}
	interface AddressForbidden {}

然后在您的Party类中,您可以这样做:

public class Party {
	@NotNull(groups = AddressRequired.class) // 用于接收者
	@Null(groups = AddressForbidden.class)   // 用于发送者
	String address;
}

最后,在Transfer类中,您可以将默认组转换为您需要的组:

public static class Transfer {
	@ConvertGroup(to = AddressForbidden.class) // 默认情况下为 from = Default.class
	@Valid
	Party sender;
	@Valid
	@ConvertGroup(to = AddressRequired.class)
	Party receiver;
}

有关组转换的更多详细信息,请参阅参考文档 - Group conversion

英文:

You could try to go with @ConvertGroup. You'll need two groups for sender/receiver cases:

	interface AddressRequired {}
	interface AddressForbidden {}

then in your party class you'd do something like

public class Party {
	@NotNull(groups = AddressRequired.class) // for receiver
	@Null(groups = AddressForbidden.class)   // for sender
	String address;
}

and finally, in the transfer class you convert default group to the one you need:

public static class Transfer {
	@ConvertGroup(to = AddressForbidden.class) // from = Default.class is set by default
	@Valid
	Party sender;
	@Valid
	@ConvertGroup(to = AddressRequired.class)
	Party receiver;
}

For more details on converting groups see the reference - Group conversion

huangapple
  • 本文由 发表于 2023年6月22日 14:14:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529025.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定