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 sSatur开发者_如何学Pythondays;
@NotNull
private Boolean sSundays;
public Scheduler() {
}
}
Can anyone please help me in writing the mentioned constraint.
Thanks!!!!!!!!!
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();
}
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
精彩评论