微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在JPA中

如何解决在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 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。