我正在寻找一种有效的方法来保留一周中的某几天。换句话说,用户将从工作日列表中选择任意天数。特定日期无关紧要,仅是星期几。我需要将这几天存储在休眠实体中。
我可以存储其中之一:
Set<DayOfWeek>
Set<Integer>
但是我认为这可能会更简单。如果我只使用一个int来存储数据并使用按位运算该怎么办。例如:
Sun = 1
Mon = 2
Tue = 4
Wed = 8
Thu = 16
Fri = 32
Sat = 64
因此,为了表示星期日,星期一,星期三和星期六的集合,我将保留整数75。这是因为1 + 2 + 8 + 64 = 75。
我关心的是在这样的字段上执行查询。我能找到所有已选择周三的实体吗?
这似乎是个好方法吗?有谁有更好的主意吗?
谢谢!
最佳答案
您可以使用Enum设置星期几
public enum DAYS_OF_THE_WEEK {
SUN,
MON,
TUE,
WED,
THU,
FRI,
SAT;
}
由于Hibernate支持,因此现在可以使用值类型的集合。
@CollectionOfElements
@Enumerated(EnumType.STRING)
@JoinTable(
name="SELECTED_DAYS_OF_THE_WEEK",
joinColumns=@JoinColumn(name="<OWNING_ENTITY_ID_GOES_HERE>")
)
public Set<DAYS_OF_THE_WEEK> getSelectedDays() {
return this.selectedDays;
}
不要忘记复合元素的寿命,或者值类型实例的寿命受所属实体实例的寿命的限制。
如前所述:
我能找到所有已选择周三的实体吗?
是
select distinc OwningEntity _owningEntity inner join fetch _owningEntity.selectedDays selectedDay where selectedDay = :selectedDay
query.setParameter("selectedDay", DAYS_OF_THE_WEEK.WED);
query.list();
已添加到原始答案:如何实现FetchingStrategy
假设以下模型
@Entity
public class Customer {
private List<Order> orderList = new ArrayList<Order>();
// getter's and setter's
}
现在我们的界面CustomerRepository
public interface CustomerRepository {
Customer getById(Integer id, CustomerFetchingStrategy fetchingStrategy);
List<Customer> getAll(CustomerFetchingStrategy fetchingStrategy);
public static enum CustomerFetchingStrategy {
PROXY,
CUSTOMER,
CUSTOMER_WITH_ORDERS;
}
}
我们的实施
import static br.com.app.CustomerRepository.CustomerFetchingStrategy;
public class CustomerRepositoryImpl implements CustomerRepository {
// Usually Spring IoC or Seam @In-jection or something else
private SessionFactory sessionFactory;
public Customer getById(Integer id, CustomerFetchingStrategy fetchingStrategy) {
switch(fetchingStrategy) {
case PROXY:
return (Customer) sessionFactory.getCurrentSession().load(Customer.class, id);
case CUSTOMER:
return (Customer) sessionFactory.getCurrentSession().get(Customer.class, id);
case CUSTOMER_WITH_ORDERS:
return (Customer) sessionFactory.getCurrentSession().createQuery("from Customer c left join fetch c.orderList where c.id = :id")
.setParameter("id", id)
.list().get(0);
}
}
public List<Customer> getAll(CustomerFetchingStrategy fetchingStrategy) {
// Same strategy as shown above
}
}
因此,是否某些用例仅需要CUSTOMER,我打电话
import static br.com.app.CustomerRepository.CustomerFetchingStrategy;
public class SomeController {
// Again Spring Ioc or Seam @In-jection
private CustomerRepository customerRepository;
public void proccessForm(HttpServletRequest request, HttpServletResponse response) {
request.setParameter("customer", customerRepository.getById(Integer.valueOf(request.getParameter("customerId"))), CUSTOMER);
}
}
希望对您有用
问候,