gpt4 book ai didi

jpa - Spring Data JPA Projection嵌套列表投影接口(interface)

转载 作者:行者123 更新时间:2023-12-05 08:11:23 25 4
gpt4 key购买 nike

我对嵌套列表投影接口(interface)的使用有疑问。我有两个实体( parent 和 child )(他们有单向关联)

父 =>

@Table(name = "parent")
@Entity
public class ParentEntity {

@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

private String name;

// other fields........
}

child =>

@Table(name = "child")
@Entity
public class ChildEntity {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@NonNull
private String name;

@NonNull
@ManyToOne(fetch = FetchType.LAZY)
private ParentEntity parent;

// other fields........
}

我有两个用于选择特定列的投影界面。

父投影 =>

public interface ParentProjection {

String getName();

Set<ChildProjection> getChild();
}

child 投影 =>

public interface ChildProjection {

String getId();

String getName();
}

我想获取包含在 ChildProjection 列表中的 ParentProjection 列表。

像这样的存储库查询=>

@Query("select p.name as name, c as child from ParentEntity p left join ChildEntity as c on p.id = c.parent.id")
List<ParentProjection> getParentProjectionList();

此查询有效,但它选择了 ChildEntity 的所有列,并且仅将 id、name 属性映射到 ChildProjection。 (生成的查询选择所有列,但我只想选择 id 和 name 列)

如何只选择 id 和 name 列(为嵌套列表投影界面选择特定列)并映射到 ChildProjection 字段(与 @Query 一起使用)?

注意:我不需要使用类类型投影。

最佳答案

您需要将 OneToMany 关系添加到 ParentEntity 并使用 Lazy 进行注释。

希望对您有所帮助(我已经试过了)

关于jpa - Spring Data JPA Projection嵌套列表投影接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57845717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com