如何使用Spring Data JPA实现嵌套对象的Java Projection?
解决Spring Data JPA Projection映射嵌套集合的问题
当然可以通过Java Projection获取嵌套数据,你的写法存在几个需要调整的地方:
1. 为嵌套实体定义对应的Projection接口
不能直接在RecipeProjection里用实体类Ingredient,需要给Ingredient单独定义一个Projection接口,只暴露你需要的字段:
public interface IngredientProjection { String getName(); // 若需要其他字段,比如id,可添加Long getId(); }
2. 修改主Projection的嵌套集合类型
把RecipeProjection里的List<Ingredient>替换成刚定义的List<IngredientProjection>:
public interface RecipeProjection { Long getId(); String getTitle(); List<IngredientProjection> getIngredients(); }
3. 调整查询语句,确保关联数据被正确加载
你之前的原生SQL返回的是扁平结构的结果,Spring Data无法自动将多行Ingredient数据合并到单个Recipe的集合中。推荐用JPQL结合FETCH JOIN来加载关联数据,让Projection自动映射嵌套集合:
@Query("SELECT r FROM Recipe r LEFT JOIN FETCH r.recipeIngredients ri LEFT JOIN FETCH ri.ingredient") List<RecipeProjection> getData();
注意:这里假设你的实体类已经定义了正确的关联关系:
Recipe实体包含List<RecipeIngredient> recipeIngredients属性RecipeIngredient实体包含Ingredient ingredient属性
如果坚持使用原生SQL,需要手动处理结果分组,实现起来比较繁琐,因此优先推荐JPQL的方式。
另外,你Repository方法的返回类型List<RecipeSearchProjection>和定义的RecipeProjection不匹配,需要统一两者的名称。
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

