简体   繁体   中英

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 . 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. 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.

There is no a specific way to do what you need using JPQL. Instead, you can use a Hibernate ResultTransformer , that allows yo to transform the query results to whatever you need. 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.

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