将GROUP BY和ORDER BY与对象上的JPA存储库一起使用

dffbzjpn  于 2022-09-18  发布在  Spring
关注(0)|答案(1)|浏览(170)

我有两个实体:

项目:

@Entity
@Table(name = "item", schema = "public")
public class ItemEntity {
    @ManyToOne
    @JoinColumn(name = "owner", nullable = false)
    private UserEntity user;
    ....
}

ItemView:

@Entity
@Table(name = "item_view", schema = "public")
public class ItemViewEntity {
    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false)
    private UserEntity user;

    @ManyToOne
    @JoinColumn(name = "item_id", nullable = false)
    private ItemEntity item;
}

我想按查看时间的长短来退还用户项目

public interface ItemViewRepository extends JpaRepository<ItemViewEntity, Long> {
   @Query("Select u.item from ItemViewEntity u WHERE u.item.owner= ?! group by u.item order by count(u.item") desc")
   List<ItemEntity> getItemsByViews(UserEntity user);
}

使用此查询时出现错误“

ERROR: column "itementi1_.id" must appear in the GROUP BY clause or be used in an aggregate function

我在每个实体上定义了所有equals方法

我尝试在基元类型上使用GROUP BY等,它们都很有效。看来我的关系有问题。

我如何解决这个问题并使查询正常工作?

mwngjboj

mwngjboj1#

您可以通过在查询中显式指定连接来完成此操作

@Query("SELECT i, COUNT(v) AS viewcount " +
            "FROM ItemViewEntity v " +
            "JOIN v.item i " +
            "WHERE i.user = ?1 " +
            "GROUP BY i " +
            "ORDER BY viewcount DESC")
    List<ItemEntity> getItemsByViews(UserEntity user);

相关问题