Modelling multiple days of the week
This is the second time i've come accross a one-many relationship between object and weekday and I'm not sure if i'm modelling it in the best way:
@Entity
MyObject {
private int id;
private String foo;
private boolean monday;
private boolean tuesday;
private boolean wednesday;
private boolean thursday;
private boolean friday;
private boolean saturday;
private boolean sunday;
}
Has anyone come across a better way of doing this?
My requirement is to retrieve all instances of MyObject
from the db that match the current day of the week, i.e. no need to check multiple days for example 开发者_Python百科mon=1 && tues=1
When modeling a finite number of items in a set, it is usually best to use an enum
.
public enum DayOfWeek {
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
You might use this in your class like so:
class YourClass {
private Set<DayOfWeek> activeDays;
public void addActiveDay(DayOfWeek day){
activeDays.add(day);
}
}
...
yourclass.addActiveDay(DayOfWeek.Friday);
How about create an enum of days of the week, and then have a private array that stores the days that are applicable? If you want to get fancy, you could have some structure (such as a Set
, which I think does not allow duplicates) other than an array that prevents duplicates.
If you're also using this with a database, what kind of query are you running to get data, and what kind of table structure are you using (enum solutions may not work with all databases)?
精彩评论