【问题标题】:JPA @Query to count how many relations each object hasJPA @Query 计算每个对象有多少关系
【发布时间】:2021-01-15 21:59:05
【问题描述】:

我一直在尝试在连接表中获取查询,以实现多对多关系的工作。该查询旨在计算有多少用户关注特定游戏。实体本身很简单,看起来像这样:

@Entity
@Table(name = "followed_users_games", uniqueConstraints = {
        @UniqueConstraint(columnNames = "followed_id")
})
public class FollowedEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "followed_id", unique = true, nullable = false)
    private Integer followedId;

    @ManyToOne
    @JoinColumn(name = "game_id")
    private GameEntity games;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private UserEntity users;

    @Column(name = "notify")
    @NonNull private Boolean notify;
}

我一直试图运行的查询看起来像这样

    @Query("select f.gameId, count(f) as usercount from FollowedEntity f group by f.games.gameId order by usercount desc")
    List<GameEntity> findMostFollowed(Pageable pageable);

我已经在我的数据库本身上测试了查询,它似乎工作正常。但是,我的应用程序会返回这样的错误:

org.postgresql.util.PSQLException: ERROR: column "gameentity1_.game_id" must appear in the GROUP BY clause or be used in an aggregate function

任何帮助将不胜感激。

【问题讨论】:

  • 我相信按 f.gameId 分组是要走的路

标签: java spring postgresql hibernate jpa


【解决方案1】:

看起来您必须在查询中使用联接,例如

@Query(value = "SELECT g.gameId, COUNT(g) as usercount FROM FollowedEntity f JOIN f.games g GROUP By g.gameId ORDER BY usercount DESC")
   List<GameEntity> findMostFollowed(Pageable pageable);

【讨论】:

    【解决方案2】:
    1. 您尝试将一对 (game_id, count) 映射到具有不同结构的整个 GameEntity,这就是生成的 sql 查询不是您所期望的原因。

    2. mapping your query result to DTO 可能对您有帮助。

    3. 每当您遇到此类问题时,我都会建议您查看 JPA 生成的 SQL 查询。参见,例如,https://www.baeldung.com/sql-logging-spring-boot

    【讨论】:

      猜你喜欢
      • 2019-04-07
      • 2019-04-30
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 2019-07-24
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多