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

问题描述 投票:0回答:2

我有以下投影类,我想通过在 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获取嵌套数据呢?

java spring spring-boot spring-data-jpa projection
2个回答
1
投票

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

尝试将你的方法定义为:

List<RecipeSearchProjection> findAllBy();

但是,投影也可以与

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


0
投票

我不建议使用基于界面的投影。它显示系统中的 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

换句话说,它比使用普通实体类进行的查询要慢。

© www.soinside.com 2019 - 2024. All rights reserved.