通过连接表的 @OrderColumn 对 JPA 查询的结果集合进行排序

问题描述 投票:0回答:1

我的 Micronaut 3.0.3 应用程序中有以下实体。

public class Game extends BaseEntity {
  ...
  @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
  @ToString.Exclude
  @OrderColumn(name = "sort_index")
  private List<Question> questions = new ArrayList<>();
  ...
}

public abstract class Question extends BaseEntity {
... // omitted
}

当我通过关卡访问问题时,顺序列效果很好,这样 Hibernate 就可以为我处理顺序:

// (pseudo) ordered correctly:
gameRepository.findById(id).getQuestions();

但是我想直接使用问题存储库,就像这样:

  @Query(
  """
      select q from Question q, Game g
      where g.id = :game
      and q in elements(g.questions)

----> order by sort_index of game_questions table
  """)
  Collection<Question> findAllByGame(UUID game);

需要帮助解决问题的排序部分。

hibernate spring-data-jpa sql-order-by micronaut micronaut-data
1个回答
0
投票

解决方案是使排序列可用作映射属性或使用本机查询

如果您没有中间 JoinTable 并且您的“问题”具有“游戏”实体的外键,则非常简单,您可以将订单列添加为“问题”实体中的属性。

public abstract class Question extends BaseEntity {

   ...
    @Column(name = "sort_index ", insertable = false, nullable = false, updatable = false)
    @Getter
    private Integer sortIndex;

}

存储库中的查询可能如下所示

public interface QuestionRepository extends JpaRepository<Question, Integer>,

    @Query("SELECT q FROM Game g "
            + "JOIN g.questions AS q "
            + "WHERE g.name = :name "
            + "ORDER BY q.sortIndex ASC")
    List<Questions> findQuestionsByName(@Param("name") String name);

如果您的数据模型更复杂并且您有一个中间

@JoinTable
,即“game_questions”,那么我通过引入一个“虚拟”关系类作为实体来解决这个问题,然后我将其用作 JPA 查询中的连接来访问排序我正在使用
@OrderColumn

的属性

这是一个高级示例:

JPA 在多对多关系中按列排序

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.