英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论