javaspringspring-bootspring-data-jpaprojection

Java Projection for nested objects using Spring Data JPA?


I have the following projection class and I want to retrieve data by joining Recipe and Ingredient tables from db using @Query in Spring data JPA:

public interface RecipeProjection {

        Long getId();
        String getTitle();
        
        List<Ingredient> getIngredients();
}

However, I cannot map the ingredients to the projection. Here is my query in the repository:

@Query(value = "SELECT r.id AS id, r.title, i.name AS ingredientName " +
        "FROM Recipe r " +
        "LEFT JOIN RecipeIngredient ri ON r.id = ri.recipeId " +
        "LEFT JOIN Ingredient i ON ri.ingredientId = i.id "
)
List<RecipeSearchProjection> getData();

I am not sure if using a proper alias for ingredient table can solve the problem, but even I tried, I cannot retrieve its data. So, is it possible to get nested data via Java Projection?


Solution

  • I suggest using query methods where queries are derived from the method name directly without writing them manually. When interface-based projections are used, the names of their methods have to be identical to the getter methods defined in the entity class.

    Try to define your method as:

    List<RecipeSearchProjection> findAllBy();
    

    However, projections can also be used with @Query annotation. For more details on the different ways to use JPA query projections, check out the blog post.