Search code examples
javajpaspring-datajpqlspring-repositories

Spring data repository group by column, list of object with other columns


How to get Spring repository return a custom DTS, which is grouping by the column businessValue1 in the table, and have a list of DTO object with other columns in the table

The table, from which I want to return the DTS

id | businessValue1 | businessValue2 | businessValue3
1  | "x"            | "uigaiun"      | "guthgi"
2  | "x"            | "rktjuhngit"   | "ujgthniuertn"
3  | "x"            | "nguitren"     | "ikljugnbe"
4  | "y"            | "iughnuitn"    | "eiubgnuie"
5  | "q"            | "rtiluhn"      | "iljughbl"
6  | "q"            | "tkiruln"      | "jutgnhet"

The Java Entity class representing the table

@Data
@AllArgsConstructor
@Entity
public class SomeEntity {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @NotNull
  private long id;
  
  @NotNull
  private String businessValue1;
  
  @NotNull
  private String businessValue2;
  
  @NotNull
  private String businessValue3;
}

The target Classes:

The DTO representation the other columns in the table

@Data
@AllArgsConstructor
public class SomeDTO {

  private String businessValue2;
  
  private String businessValue3;
}

The DTS representation the group by of the column businessValue1, with the other columns as a list of DTOs

@Data
@AllArgsConstructor
public class SomeDTS {

  private String businessValue1;
  
  private List<SomeDTO> dtos;
}

My expected outcome will have a structure like below

├── "x"
|    ├── "uigaiun", "guthgi"
|    ├── "rktjuhngit", "ujgthniuertn"
|    └── "nguitren", "ikljugnbe"
|
├── "y"
|    └── "iughnuitn", "eiubgnuie"
|
└── "q"
     ├── "rtiluhn", "iljughbl"
     └── "tkiruln", "jutgnhet"

I was thing that the Spring Data Repository interface should look something like below

@Repository
public interface SomeEntityRepository extends JpaRepository<SomeEntity, Long> {

  @Query(
      "SELECT "
      +  "new SomeDTS "
      +"FROM "
      +  "SomeEntity s "
      +"GROUP BY "
      +  "s.businessValue1")
  public List<SomeDTS> SomeEntityGroupByBusinessValue1();

}

By I'm struggling to JPQL query just right, can anyone please help me?

UPDATE 1 - Nov 19th 2020:

I think I got a bit closer, with the comment from @Zorglube

@Repository
public interface SomeEntityRepository extends JpaRepository<SomeEntity, Long> {

  @Query(value =
      "SELECT "+
          " DISTINCT SomeDTS.businessValue1, SomeDTO" +
          " FROM SomeEntity AS SomeDTS" +
          " JOIN SomeEntity AS SomeDTO ON SomeDTS.businessValue1 = SomeDTO.businessValue1")
  Stream<SomeDTS> SomeEntityGroupByBusinessValue1();

}

This still give me issues with mapping

No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [SomeDts]
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [SomeDts]
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:194)
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:174)
    at org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.convert(ResultProcessor.java:297)
    at org.springframework.data.repository.query.ResultProcessor$ChainingConverter.lambda$and$0(ResultProcessor.java:217)
    at org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:228)
    at org.springframework.data.repository.query.ResultProcessor.lambda$processResult$0(ResultProcessor.java:163)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
    at org.hibernate.query.spi.StreamDecorator.collect(StreamDecorator.java:211)    
.
.
.

So how to make the mapping?

Update 2 Switching to interfaces instead

@Repository
public interface SomeEntityRepository extends JpaRepository<SomeEntity, Long> {

  @Query(value =
      "SELECT "+
          " DISTINCT SomeDTSIF.businessValue1 as businessValue1, SomeDTOIF" +
          " FROM SomeEntity AS SomeDTSIF" +
          " JOIN SomeEntity AS SomeDTOIF ON SomeDTSIF.businessValue1 = SomeDTO.businessValue1")
  Stream<SomeDTSIF> SomeEntityGroupByBusinessValue1();

}

Solve the "No converter found capable of converting" issue, but I get 6 objects back:

├── "x"
|    └── NULL
|
├── "x"
|    └── NULL
|
├── "x"
|    └── NULL
|
├── "y"
|    └── NULL
|
├── "q"
|    └── NULL
|
└── "q"
     └── NULL

And the list of SomeDTOIF in the SomeDTSIF do not get mapped.


Solution

  • I ended up making a "virtual" parent entity, which acts kind of like a view

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    @Entity
    @EqualsAndHashCode
    @Immutable
    @Subselect(
        "SELECT"
            + " DISTINCT SomeEntityParent.currency_source "
            + " FROM some_entity SomeEntityParent"
            + " JOIN some_entity SomeEntity"
            + " ON SomeEntityParent.businessValue1 = SomeEntityParent.businessValue1"
    )
    public class SomeEntityParent {
    
      private String businessValue1;
      
      private List<SomeEntity> someEntity;
    }
    

    And then a Repository interface based on that

    @Repository
    public interface SomeEntityParentRepository extends JpaRepository<SomeEntityParent, Long> {
    
    }
    

    Which can then be used in services

    @Autowired
    private SomeEntityParentRepository repository;
      
    List<SomeEntityParent> results = repository.findAll();
    

    The flat structure is now a hierarchical object.