在JPA中

问题描述

我有两个桌子,分别是房间和分配。房间有空房。在分配中,我要存储正在占用房间的人。现在,我想找出每个房间可容纳的人数。

实体

@Table(name = "ALLOTMENT")
public class RoomAllotment {
    @Id
    @Column(name = "ALLOT_NO")
    private Integer allotNo;
    
    @OnetoOne
    @JoinColumn(name="RM_CD",referencedColumnName = "RM_CD")
    private RoomMaster roomCode;
   
    //some more columns
}

@Table(name = "ROOMS")
public class RoomMaster {
    @Id
    @Column(name = "RM_CD")
    private Integer roomCode;
    
    @Column(name = "ROOM_NO")
    @NotNull(message = "Room number is required")
    @Size(max=20,message = "Maximum 20 characters only")
    private String roomNo;
    
    @Column(name = "OCCUPANCY")
    @Range(min=1,max=10,message = "Occupancy can be minimum 1 or maximum 10 only")
    private Integer occupancy;

    //some more columns
}

数据库中,我具有以下值。

Room Table

RM_CD | ROOM_NO | OCCUPANCY |
-----------------------------
    1 |   A-401 |         5 |
    2 |   A-402 |         4 |

Allotment Table

ALLOT_NO | RM_CD |   OCCUPANT  |
--------------------------------
       1 |     1 |  Alex Warne |
       2 |     1 | Mike Parker |

现在我希望所有房间都保持当前状态。
1号室-> 5-(两个人住在1号室)= 3
2号房-> 4-(没有人住在2号房)= 4

如何为此编写查询。我已经写了一个查询,但它给了我错误

@Query(value = "SELECT r.roomCode,"+
                "(r.occupancy- "+
                "(SELECT COUNT(*) FROM RoomAllotment ra WHERE ra.roomCode.roomCode=r.roomCode) "+
                ") occupancy"+
                "FROM RoomMaster r "+
                "ORDER BY r.roomCode")
Page<RoomDetails> findAllVacantRooms(Pageable pageable);

错误

Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: occupancy near line 1,column 168 [SELECT r.roomCode,(r.occupancy- (SELECT COUNT(*) FROM com.datanet.model.osm.RoomAllotment ra WHERE ra.roomCode.roomCode=r.roomCode) )occupancy FROM com.datanet.model.osm.RoomMaster r ORDER BY r.roomCode]

解决方法

您可以按以下方式使用left outer joingroup by

SELECT R.roomCode,R.occupancy - COUNT(A.allotNo) AS occupancy 
  FROM ROOM R LEFT JOIN ALLOTMENT   A
    ON R.roomCode= A.roomCode
 GROUP BY R.roomCode,R.occupancy