如何处理具有实体关系的Spring Boot / Spring Data投影(嵌套投影)

时间:2019-03-27 07:17:54

标签: spring spring-boot spring-data-jpa spring-projections

我正在尝试在Spring Boot中使用嵌套的投影。我有2个实体,ParentChild,而Parent@OneToMany具有单向Child关系。

以下是类:(使用龙目岛注释)

@Entity
@Data @NoArgsConstructor
public class Parent {

    @Id
    @GeneratedValue
    private long id;
    private String basic;
    private String detail;

    @OneToMany(fetch = FetchType.EAGER)
    private List<Child> children;

    public Parent(String basic, String detail, List<Child> children) {
        this.basic = basic;
        this.detail = detail;
        this.children = children;
    }
}
@Entity
@Data @NoArgsConstructor
public class Child {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private long id;
    private String basic;
    private String detail;

    public Child(String basic, String detail) {
        this.basic = basic;
        this.detail = detail;
    }
}

在即时获取数据而不进行投影时,我得到以下信息:

[
    {
        "id": 1,
        "basic": "parent-basic-1",
        "detail": "parent-detail-1",
        "children": [
            {
                "id": 1,
                "basic": "child-basic-1",
                "detail": "child-detail-1"
            },
            {
                "id": 2,
                "basic": "child-basic-2",
                "detail": "child-detail-2"
            }
        ]
    },
    {
        "id": 2,
        "basic": "parent-basic-2",
        "detail": "parent-detail-2",
        "children": [
            {
                "id": 3,
                "basic": "child-basic-3",
                "detail": "child-detail-3"
            },
            {
                "id": 4,
                "basic": "child-basic-4",
                "detail": "child-detail-4"
            }
        ]
    }

目标是:

    {
        "id": 1,
        "basic": "parent-basic-1",
        "children": [1,2]
    },
    {
        "id": 2,
        "basic": "parent-basic-2",
        "children": [3,4]
    }

但是,实现这一目标似乎完全不可能。

  1. 到目前为止,我已经尝试过 Constructor Projection
@Value
public class ParentDto {
    long id;
    String basic;
    // wanted to get it to work with just Child instead of ChildDto first, before getting ChildDto to work
    Collection<Child> children; 

    public ParentDto(long id, String basic, Collection<Child> children) {
        this.id = id;
        this.basic = basic;
        this.children = children;
    }
}
    // Constructor Projection in Repository
    @Query("select new whz.springbootdemo.application.constructor_projection.ParentDto(p.id, p.basic, p.children) from Parent p")
    List<ParentDto> findAllConstructorProjected();

但这会导致以下错误:

could not prepare statement; SQL [select parent0_.id as col_0_0_, parent0_.basic as col_1_0_, . as col_2_0_ from parent parent0_ inner join parent_children children1_ on parent0_.id=children1_.parent_id inner join child child2_ on children1_.children_id=child2_.id]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
  1. 尝试动态投影
    // Dynamic Projection in Repository
    List<ParentDto> findAllDynamicProjectionBy();

导致以下错误:

org.hibernate.hql.internal.ast.QuerySyntaxException:
Unable to locate appropriate constructor on class [whz.springbootdemo.application.constructor_projection.ParentDto].
Expected arguments are: <b>long, java.lang.String, whz.springbootdemo.application.child.Child</b>
[select new whz.springbootdemo.application.constructor_projection.ParentDto(generatedAlias0.id, generatedAlias0.basic, children) from whz.springbootdemo.application.parent.Parent as generatedAlias0 left join generatedAlias0.children as children]; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [whz.springbootdemo.application.constructor_projection.ParentDto]. Expected arguments are: long, java.lang.String, whz.springbootdemo.application.child.Child [select new whz.springbootdemo.application.constructor_projection.ParentDto(generatedAlias0.id, generatedAlias0.basic, children) from whz.springbootdemo.application.parent.Parent as generatedAlias0 left join generatedAlias0.children as children]

基本上告诉我执行了连接,但是值arent由父代的id分组,因此导致x行,其中x是父代的孩子数,每个子代都有父子的基本信息和一个其子项信息。

  1. 唯一起作用的是接口投影
    // Interface Projection in Repository
    List<ParentDtoInterface> findAllInterfaceProjectedBy();
public interface ParentDtoInterface {
    long getId();
    String getBasic();
    List<ChildDtoInterface> getChildren();
}

public interface ChildDtoInterface {
    long getId();
}

结果为:

[
    {
        "id": 1,
        "children": [
            {
                "id": 1
            },
            {
                "id": 2
            }
        ],
        "basic": "parent-basic-1"
    },
    {
        "id": 2,
        "children": [
            {
                "id": 3
            },
            {
                "id": 4
            }
        ],
        "basic": "parent-basic-2"
    }
]

现在我对Interface-Projection的问题是,它不仅会加载预期的属性,而且会加载所有属性,但是jackson只会序列化Interface提供的属性,因为它使用了Class / Interface-Definition。

已加载父项:(sql日志;请参见第4行,已加载详细信息)

    select
        parent0_.id as id1_1_,
        parent0_.basic as basic2_1_,
        parent0_.detail as detail3_1_ 
    from
        parent parent0_

接口投影似乎也真的很慢(请参阅this Stackoverflow question),我仍然必须解开子项的包装,因为它们被指定为[{id:1},{id:2}],但我确实需要[1,2]。我知道我可以使用@JsonIdentityReference(alwaysAsId = true)来做到这一点,但这只是一种解决方法。

我也有点困惑为什么在n + 1个查询中加载数据-父母中有1个,每个父母孩子中有n个(其中n是父母的数量):

    select
        parent0_.id as id1_1_,
        parent0_.basic as basic2_1_,
        parent0_.detail as detail3_1_ 
    from
        parent parent0_

   select
        children0_.parent_id as parent_i1_2_0_,
        children0_.children_id as children2_2_0_,
        child1_.id as id1_0_1_,
        child1_.basic as basic2_0_1_,
        child1_.detail as detail3_0_1_ 
    from
        parent_children children0_ 
    inner join
        child child1_ 
            on children0_.children_id=child1_.id 
    where
        children0_.parent_id=?

//... omitting further child queries

我尝试过@OneToMany(fetch=FetchType.LAZY)@Fetch(FetchType.JOINED)-都得到与上述相同的结果。

所以主要问题是:有什么方法可以使用Spring Boot来实现嵌套实体的投影,以便仅在尽可能少的查询中加载所需的数据,在最佳情况下,我可以对其进行调整这样,我不必加载List子项,而只需加载List childIds(也许通过一个Jpa查询,该查询通过父项对连接的行进行分组,并可以从Child中提取所需的数据?)。

我正在使用Hibernate和内存数据库。

感谢您的回答或提示!

编辑:澄清一下:我并不是想找到一种以所需格式序列化数据的方法-这已经可以实现了。主要重点是仅从数据库中加载必要的信息。

1 个答案:

答案 0 :(得分:0)

这将始终获取孩子,但可以给您想要的结果。

public interface SimpleParentProjection {

    String getBasic();

    String getDetail();

    @Value("#{T(SimpleParentProjection).toId(target.getChildren())}")
    String[] getChildren();

    static String[] toId(Set<Child> childSet) {
        return childSet.stream().map(c -> String.valueOf(c.getId())).toArray(String[]::new);
    }
}