简体   繁体   中英

JPA @Query to count how many relations each object has

I've been trying to get a query inside a join table for a many to many relation working. The query was meant to count how many users follow a specific game. The entity itself is very simple, looks like this:

@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;
}

And the query I've been trying to get running looks like so

    @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);

I have tested the query on my database itself, and it seems to be working fine. However my application returns an error as such:

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

Any help would be appreciated.

It looks like you have to use join in your query like

@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);
  1. You try to map a pair (game_id, count) to the whole GameEntity that has a different structure, that's why sql query that is generated is not what you expect.

  2. What can probably help you is mapping your query result to DTO .

  3. Every time when you have an issue like this I would recommend to have a look at SQL query that JPA is generating. See, eg, https://www.baeldung.com/sql-logging-spring-boot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM