我有以下投影类,我想通过在 Spring data JPA 中使用
@Query
连接数据库中的 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 Projection获取嵌套数据呢?
我不建议使用基于界面的投影。它显示系统中的 GC 活动过多。
看看我的这个答案。
https://stackoverflow.com/a/77241396/10480017
使用基于接口的投影选择查询结果:
基准:
Benchmark Mode Cnt Score Error Units
findAll_User_JPA avgt 20 313996,003 ± 14203,533 us/op
findUserDto1_UserDto11_EntityToDTO avgt 20 117024,805 ± 4699,478 us/op
findUserDto1_UserDto1_JPQL_Query avgt 20 115913,206 ± 4862,815 us/op
findUserProjection_UserProjection_JPQL avgt 20 416818,290 ± 11266,894 us/op
换句话说,它比使用普通实体类进行的查询要慢。