Skip to content
Advertisement

How to implement JPQL query?

I have working query in PostgreSQL:

select s.id, s.seat_number as available_seat, s.row_number as available_row, rm.room_name as screening_room
from seats s
         join rooms rm on rm.id=s.room_id
         left join (
    select r.seat_id from reserved_seats r
                              join reservations  res on res.id=r.reservation_id AND res.screening_id = 3 ) res on res.seat_id=s.id
where res.seat_id is null AND s.room_id=3
ORDER BY s.id;

But I make mistakes translating it into the JPA query language.

enter image description here

Can I use nested SELECTs in JPQL?

The answer is to use native query:

@Query(value =
            "SELECT s.id seatId, s.seat_number availableSeat, " +
                    "s.row_number availableRow, rm.name screeningRoom n" +
                    "FROM seats sn" +
                    "JOIN rooms rm on rm.id=s.room_idn" +
                    "   LEFT JOIN (n" +
                    "       SELECT r.seat_id FROM reserved_seats rn" +
                    "       JOIN reservations res ON res.id=r.reservation_id " +
                    "       AND res.screening_id = :screeningId) res ON res.seat_id=s.idn" +
                    "WHERE res.seat_id IS NULL AND s.room_id=:roomId AND s.row_number=:rowNumbern" +
                    "ORDER BY s.id;", nativeQuery = true)

Advertisement

Answer

The answer is to use native query:

@Query(value =
            "SELECT s.id seatId, s.seat_number availableSeat, " +
                    "s.row_number availableRow, rm.name screeningRoom n" +
                    "FROM seats sn" +
                    "JOIN rooms rm on rm.id=s.room_idn" +
                    "   LEFT JOIN (n" +
                    "       SELECT r.seat_id FROM reserved_seats rn" +
                    "       JOIN reservations res ON res.id=r.reservation_id " +
                    "       AND res.screening_id = :screeningId) res ON res.seat_id=s.idn" +
                    "WHERE res.seat_id IS NULL AND s.room_id=:roomId AND s.row_number=:rowNumbern" +
                    "ORDER BY s.id;", nativeQuery = true)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement