从 JPA 中的 2 个查询中减去结果

Posted

技术标签:

【中文标题】从 JPA 中的 2 个查询中减去结果【英文标题】:Subtract result from 2 queries in JPA 【发布时间】:2021-02-22 03:48:24 【问题描述】:

我有两张桌子,即房间和分配。房间有人入住。在分配中,我正在存储占用房间的人。现在我想知道每个房间的入住人数。

实体

@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]

【问题讨论】:

【参考方案1】:

您可以使用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 

【讨论】:

以上是关于从 JPA 中的 2 个查询中减去结果的主要内容,如果未能解决你的问题,请参考以下文章

从当前查询中减去子查询中的行数

减去两个查询结果

查询中的 JPA 似乎没有返回任何结果

JPA:如何将原生查询结果集转换为 POJO 类集合

从 Spring Data Jpa 运行查询时无法获得结果

JPA 查询未在列表中返回更新的结果