[英]How do I map 1 column of a SINGLE table query to a COLLECTION using Spring JPA/Hibernate
Id like to know if there's a way of doing something like the Stream API groupingBy Collector .我想知道是否有办法做类似 Stream API groupingBy Collector 的事情。 I know how to select one column (the question was marked as duplicated and I don't belive it is) I want to do a grouping ( like the groupingBy collector of the java Stream API ) not a group By.
我知道如何选择一列(问题被标记为重复,我不相信它是)我想做一个分组(比如 java Stream API 的 groupingBy 收集器)而不是一个 group By。 Suppose you have a table (ONE table) like:
假设您有一张桌子(一张桌子),例如:
+---------------------+
+ myTable +
+----------+----------+
+ column_A | column_B +
+----------+----------+
+ 1 | 1 +
+ 1 | 2 +
+ 1 | 3 +
+ 2 | 1 +
+----------+----------+
And I would like to have something like我想要一些类似的东西
@Entity
@Table("MyTable")
public class MyEntity {
@Column("column_A")
private int a;
@Column("column_B") ?
private List<Integer> b; //normanly this wuould just be int b, butI want a list of all b's that have the same a
}
with a repo like与回购类似
public interface MyCrudRepo extends CrudRepository<MyEntity,Integer>{
List<MyEntity> findByA();
}
or或者
public interface MyCrudRepo extends CrudRepository<MyEntity,Integer>{
@Query("SELECT m.a,m.b FROM MyEntity m")
List<MyEntity> customFind();
}
This is not necessarily how it should look at the end, anything that works similar to this is fine.这不一定是它最终应该如何看待,任何与此类似的工作都很好。 I have looked into projections but all examples use 2 different tables.
我研究了预测,但所有示例都使用 2 个不同的表。
There is no a specific way to do what you need using JPQL.没有特定的方法可以使用 JPQL 执行您需要的操作。 Instead, you can use a Hibernate ResultTransformer , that allows yo to transform the query results to whatever you need.
相反,您可以使用 Hibernate ResultTransformer ,它允许您将查询结果转换为您需要的任何内容。 This is a code solution, and is similar to implementing the grouping using the Stream API in the list result and return a map containing the aggregated data.
这是一个代码解决方案,类似于在列表结果中使用Stream API实现分组并返回包含聚合数据的映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.