一尘不染

Hibernate:使用一对多限制查询

hibernate

例如,我有Service实体:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "service")
public List<ServiceStatus> getServiceStatuses() {
    return serviceStatuses;
}

ServiceStatus实体:

@ManyToOne
@JoinColumn(name = "service", nullable = false)
public Service getService() {
    return service;
}

@Column(name = "date", nullable = false)
@Temporal(TemporalType.DATE)
public Date getDate() {
    return date;
}

现在,我需要查询所有Service对象,以便每个ServiceStatus对象仅ServiceStatus.date具有介于date1和之间的那些对象date2。也就是说,如果有10个ServiceStatus具有正确日期的对象,则serviceStatuses列表将仅包含那10个对象,仅此而已。可能吗?

提前致谢。


阅读 354

收藏
2020-06-20

共1个答案

一尘不染

我使用@Filter解决了问题:

@FilterDef(name = "dateFilter", parameters = {
        @ParamDef(name = "date1", type = "date"),
        @ParamDef(name = "date2", type = "date") })
@Filter(name = "dateFilter", condition = "date >= :date1 and date <= :date2")

并将其应用于会话:

session.enableFilter("dateFilter")
                .setParameter("date1", date1)
                .setParameter("date2", date2);

顺便说一句,在使用Hibernate时,应该使用什么查询:它是自己的机制还是“原始” SQL(例如“内部联接”)?

2020-06-20