spring-data-jpajpa-2.0jpa-2.1

Spring JPA Class-based Projections and Nested projections


I am trying to use the Class-based Projections to fill the data but seems the Spring JPA does not support the nested projection. Here is my entity class:

public class Category extends BaseEntity<String> {

    @Column(unique = true)
    private String code;

    private String externalCode;

    @ManyToOne(cascade = CascadeType.ALL)
    private Category parent;

    ..
}

Here is the DTO class for same:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class CategoryDto implements BaseDto, Serializable {
    private String code;
    private String externalCode;
    private CategoryDto parent;
    ..
}

My CategoryRepository

@Query("select new com.easycart.core.data.category.CategoryDto(c.id,c.code,c.externalCode,c.seoMeta, c.createdAt, c.updatedAt,c.parent) FROM Category c where c.code = :code")
        CategoryDto findCategoryByCode(String code);

I can't use the c.parent as the type is Category and not the CategoryDto, also I did not find any option to use the nested projection to fill the parent information for the given entity. Can someone help me with following questions?

  1. Is there a way to achieve this using class based projection?
  2. DO I need to fallback to the option to fill the parent information separately (I don't need lot of information for the parent in the initial load.).
  3. Any other way to achieve this? I don't want to use the interface based projection as initial test showing it's very slow as compare to class based projection.

Solution

  • There is no out of the box support for this in Spring Data JPA. The way to achieve this is to use constructor expressions and ResultTransformer