Java投影嵌套对象使用Spring Data JPA?



我有以下投影类,我想通过在Spring数据JPA中使用@Query从db中连接Recipe和Ingredient表来检索数据:

public interface RecipeProjection {
Long getId();
String getTitle();

List<Ingredient> getIngredients();
}

然而,我不能将成分映射到投影。以下是我在存储库中的查询:

@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();

我不确定是否使用正确的别名成分表可以解决问题,但即使我尝试,我无法检索其数据。那么,有可能通过Java投影获得嵌套数据吗?

我建议使用直接从方法名派生的查询方法,而不需要手动编写查询方法。当使用基于接口的投影时,其方法的名称必须与实体类中定义的getter方法相同。

尝试将你的方法定义为:

List<RecipeSearchProjection> findAllBy();

但是,投影也可以用于@Query注释。有关使用JPA查询投影的不同方法的更多详细信息,请查看博客文章。

最新更新