提问者:小点点

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


我正在尝试让嵌套投影在Spring Boot中工作。我有2个实体,父母孩子,而父母孩子有一个单向的@OneTo多关系。

以下是类:(使用Lombok注释)

@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. 到目前为止,我已经尝试过构造函数投影:
@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
    // 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]

这基本上告诉我执行了一个连接,但是值没有按父节点的id分组,因此产生了x行,其中x是父节点拥有的子节点数,每个子节点都有父节点的基本信息和一个子节点信息。

    // 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"
    }
]

现在我对接口投影的问题是,它不仅会加载预期的属性,还会加载所有属性,但jackson只会序列化接口提供的那些属性,因为它使用类/接口定义。

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

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

此外,接口投影似乎真的很慢(参见这个Stackoverflow问题),我仍然必须解压缩子级,因为它们被给出为[{id: 1},{id:2}],但我真的需要[1,2]。我知道我可以用@JsonIdtyApplication(alwaysAsId=true)来做到这一点,但这只是一种解决方法。

我也有点困惑为什么数据在n个查询中加载-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

我尝试过@OneTo很多(fetch=FetchType. LAZY)@Fetch(FetchType.JOINED)-两者都给出了与上述相同的结果。

所以主要的问题是:有什么方法可以实现嵌套实体的Spring Boot投影,以便在尽可能少的查询中只加载所需的数据,在最好的情况下,我可以调整它,而不是加载List子项,我可以只加载List子项(也许通过Jpa查询,将连接的行按括号分组,让我们从子项中提取所需的数据?)。

我使用Hibernate和内存数据库。

感谢您的任何回答或提示!

编辑:澄清一下:我并没有试图找到一种方法来序列化所需格式的数据——这我已经可以实现了。主要关注点是只从数据库中加载必要的信息。


共1个答案

匿名用户

这将永远吸引孩子,但可以给你你想要的结果。

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);
    }
}