复杂的SQL查询到Hibernate HQL语句

时间:2012-08-07 13:14:37

标签: java sql hibernate hql

以下SQL查询:

select distinct hotel.country 'Country', hotel.id 'Hotel ID', hotel.Name'Name', room.id 'Room ID'
from room, stay, reservation, hotel
where
(stay.roomid = room.id) 
and (stay.reservationid = reservation.id) 
and (reservation.status != 'Booked' AND reservation.status != 'CheckedIn')
and (reservation.arrivaldate >= '2012-08-08')
and (reservation.leavedate <= '2012-08-15')
and (room.hotelid = hotel.id)
order by hotel.country, hotel.id, hotel.name, room.id asc

这将为我提供每个国家/地区每个酒店的可用房间列表。现在我必须把它放在HQL中,但我不能这样做:

Query query = session.createQuery("from room, stay, reservation, hotel where stay.roomid = room.id");

这不起作用因为stay.roomid是一个Room对象,而room.id只是一个整数。我对Hibernate / HQL很陌生,参考手册并没有真正把我带到任何地方......我怎样才能转换&#34; (可怕的一句话,我知道这并不涉及实际转换)这个SLQ查询到HQL语句?感谢。

更新

在同一问题中使用联接结果

Query query = session.createQuery("" +
                    "from Stay stay " +
                    "join stay.ReservationID reservation " +
                    "join stay.RoomID room " +
                    "join room.HotelID hotel " +
                    "where (stay.RoomID = room.ID)");

我真的错过了一些东西(可能非常符合逻辑)......

1 个答案:

答案 0 :(得分:1)

您没有显示您的实体,但是,就像您在SQL中使用连接一样,您需要在HQL中使用连接:

select ...
from Stay stay
join stay.reservation reservation
join stay.room room
join rom.hotel hotel
where (reservation.status != 'Booked' AND reservation.status != 'CheckedIn')
and (reservation.arrivaldate >= '2012-08-08')
and (reservation.leavedate <= '2012-08-15')

Hibernate文档有一整章关于HQL,本章的一节是关于associations in HQL的。