如何编写自定义约束来检查类中至少一个布尔字段是否为 true

发布于 2024-11-09 14:14:28 字数 494 浏览 0 评论 0原文

我有一个名为“Scheduler”的类,它有 7 个布尔字段。我想在休眠中编写一个约束来检查至少一个布尔字段是否为真。

这是“调度程序”类。

public class Scheduler {

private String description;

@NotNull
private Boolean sMondays;

@NotNull
private Boolean sTuesdays;

@NotNull
private Boolean sWednesdays;

@NotNull
private Boolean sThursdays;

@NotNull
private Boolean sFridays;

@NotNull
private Boolean sSaturdays;

@NotNull
private Boolean sSundays;

public Scheduler() {

}
}

谁能帮我写一下提到的约束。

谢谢!!!!!!!!!

I have a class called "Scheduler" which has 7 Boolean fields. I want to write a constraint in hibernate to check that at-least one boolean field is true.

Here is the "Scheduler" class.

public class Scheduler {

private String description;

@NotNull
private Boolean sMondays;

@NotNull
private Boolean sTuesdays;

@NotNull
private Boolean sWednesdays;

@NotNull
private Boolean sThursdays;

@NotNull
private Boolean sFridays;

@NotNull
private Boolean sSaturdays;

@NotNull
private Boolean sSundays;

public Scheduler() {

}
}

Can anyone please help me in writing the mentioned constraint.

Thanks!!!!!!!!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷心人i 2024-11-16 14:14:28

这很复杂,因为您使用的是布尔值而不是原始布尔值,这会产生空指针异常的风险。

为了简化逻辑,我将修改每个字段声明以将其初始化为 false。当您将它们注释为 @NotNull 时,我的假设是这将适用于您现有的业务逻辑。

如果您这样做,则可以使用 || 轻松验证至少一个为真:

public boolean validateAtLeastOneIsTrue() {
    return getsMondays() || getsTuesdays() || getsWednesdays()
    || getsThursdays() || getsFridays() || getsSaturdays()
    || getsSundays();
}

This is complicated because you're using Booleans instead of the primitive boolean, which creates the risk of null pointer exceptions.

To simplify the logic, I'd modify each field declaration to initialize it to false. As you've annotated them as @NotNull, my assumption is this will work with your existing business logic.

If you do this, your validation for at least one is true is quite simply achieved using ||:

public boolean validateAtLeastOneIsTrue() {
    return getsMondays() || getsTuesdays() || getsWednesdays()
    || getsThursdays() || getsFridays() || getsSaturdays()
    || getsSundays();
}
感性不性感 2024-11-16 14:14:28

在不知道您正在工作的确切域的情况下,我建议使用时间数据类型,例如日历。这将允许您在一周的当前日期进行简单的查找。它还使代码更易于维护

Without knowing the exact domain you are working in I would recommend using a temporal data type such as Calendar. This will allow you to do a simple lookup on the current day of the week. It also makes the code far more maintainable

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文