首页 > 解决方案 > 如何在jpa中以一对多关系选择孩子

问题描述

我想选择我想要的有孩子的父母。

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

我怎样才能做到这一点?

例子:

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)-> 孩子(类型)

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

标签: javaspring-bootjpaspring-datajpql

解决方案


在我看来,您正在尝试建立双向关系。这可以通过将映射添加到关系的两侧来实现。

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

@Entity
public class Child {
    @Id
    private Integer id;
    @ManyToOne
    @JoinColumn(name = "parentId")
    private Parent parent;
    // Remove parentId field

    // Getters + Setters ...
}

注意:如果要保留该parentId字段,则必须选择要用于插入和更新实体的两个映射 (getParentId()或)。getParent().getId()另一个字段应该同时具有insertable = falseupdatable = false

下一步是更改@OneToMany要使用的映射mappedBy

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

    // Getters + Setters ...
}

如果要检索特定子项及其父项,您现在可以为Child实体创建一个存储库:

public interface ChildRepository extends JpaRepository<Child, Integer> {

}

之后,您可以使用以下方法获取特定的孩子:

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

使用 Spring boot 1.x 将是:

Child child = repository.findOne(123);
Parent parent = null;
if (child != null) {
    parent = child.getParent();
}

推荐阅读