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