我有一个日历和一个房间实体。
我的日历实体如下所示:
public class CalendarEntity {
@EmbeddedId
private CalendarId calendarId = new CalendarId();
@Basic
@Column(name = "available", nullable = false)
private Boolean available;
@Basic
@Column(name = "price")
private double price;
@ManyToOne
@JoinColumn(name = "room_id", referencedColumnName = "id", insertable =
false, updatable = false)
private RoomEntity roomEntity;
}
@Embeddable
public class CalendarId implements Serializable {
@Column(name= "date", nullable = false)
private Date date;
@Column(name = "room_id", nullable = false)
private Integer room_id;
}
我的房间实体看起来像这样:
public class RoomEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id", nullable = false, unique = true)
private Integer id;
}
我们假设我在日历实体中有一些条目2017-10-5, 2017-10-6,2017-10-7,2017-10-8 with room_id = 10.
我想构建一个查询,这样如果用户要求一个房间有一定的签到和结账日期,那么他将获得正确的房间列表。
我该怎么做?
例如,用户要求checkin = 2017-10-6和checkout = 2017-10-8的房间,房间应该出现在列表中。
查询应该是什么,以便我得到正确的房间列表?
更新:
我现在的查询只检查房间是否在登记日期和结帐日期可用,但不在之间:
select r from RoomEntity r where r.id in (Select c1.calendarId.room_id from CalendarEntity c1, CalendarEntity c2 where (c1.calendarId.room_id = c2.calendarId.room_id) and (c1.calendarId.date =:checkin and c1.available=true) and(c2.calendarId.date =:checkout and c2.available=true))
答案 0 :(得分:1)
方法是:SELECT count(c.calendarId.room_id),c.calendarId.room_id FROM CalendarEntity c WHERE c.available = true和c.calendarId.date BETWEEN:checkin and:checkout GROUP BY c.calendarId.room_id HAVING count(c.calendarId.room_id)> =:noOfDays noODays表示从签入和退房日期计算的天数。
答案 1 :(得分:0)
SELECT r FROM RoomEntity r
WHERE r.id
in (select c1.calendarId.room_id
FROM CalendarEntity c1 JOIN CalendarEntity c2
WHERE c1.calendarId.room_id = c2.calendarId.room_id
AND ((c1.calendarId.date BETWEEN :checkin AND :checkout)
AND (c1.available=true and c2.available=true));