Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在jpa中选择一对多关系中的子级_Java_Spring Boot_Jpa_Spring Data_Jpql - Fatal编程技术网

Java 如何在jpa中选择一对多关系中的子级

Java 如何在jpa中选择一对多关系中的子级,java,spring-boot,jpa,spring-data,jpql,Java,Spring Boot,Jpa,Spring Data,Jpql,我要选择具有所需子级的父级 但是当我选择我的父母时,我必须显示所有的孩子 我该怎么做 例如: public class parent{ private Integer id; @OnetoMany @JoinColumn(name="parentId") private List<child> children; } public class child{ private Integer id; private Integer par

我要选择具有所需子级的父级

但是当我选择我的父母时,我必须显示所有的孩子

我该怎么做

例如:

public class parent{
    private Integer id;
    @OnetoMany
    @JoinColumn(name="parentId")
    private List<child> children;
}

public class child{
    private Integer id;
    private Integer parentId;
}

findByIdAndchildType(Integer id, String type)
公共类父类{
私有整数id;
@独身癖
@JoinColumn(name=“parentId”)
私人名单儿童;
}
公营儿童{
私有整数id;
私有整数父ID;
}
findByIdAndchildType(整数id,字符串类型)
我想看到:父(id)->子(类型)


但是我可以看到parent(id)->child(othertype)、child(othertype1)、child(type)

在我看来,您试图获得一种双向关系。这可以通过将映射添加到关系的两侧来实现

例如,将
@ManyToOne
映射添加到
子实体。请注意,您可能应该删除您的
parentId
字段,因为现在您可以使用
child.getParent().getId()
访问它

@实体
公营儿童{
@身份证
私有整数id;
@许多酮
@JoinColumn(name=“parentId”)
私人家长;
//删除父ID字段
//获取者+设置者。。。
}
注意:如果要保留
parentId
字段,则必须选择要用于插入和更新实体的两个映射(
getParentId()
getParent().getId()
)。另一个字段应同时具有
insertable=false
updateable=false

下一步是将
@OneToMany
映射更改为使用
mappedBy

@Entity
public class Parent {
    @Id
    private Integer id;
    @OneToMany(mappedBy = "parent") // Change this
    private List<Child> children;

    // Getters + Setters ...
}
之后,您可以使用以下命令获取特定子项:

Optional<Child> child = repository.findById(123); // 123 is the ID of the child in this case
Optional<Parent> parent = child.map(Child::getParent);
Optional<Child> child = repository.findById(123); // 123 is the ID of the child in this case
Optional<Parent> parent = child.map(Child::getParent);
Child child = repository.findOne(123);
Parent parent = null;
if (child != null) {
    parent = child.getParent();
}