【问题标题】:how to select child in one to many relation in jpa如何在jpa中以一对多关系选择孩子
【发布时间】:2018-11-13 19:30:36
【问题描述】:

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

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

我该怎么做?

例子:

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)

我想看:parent(id) -> child(type)

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

【问题讨论】:

    标签: java spring-boot jpa spring-data jpql


    【解决方案1】:

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

    例如,将@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();
    }
    

    【讨论】:

    • 相当老的帖子,但是有什么办法可以跳过子查找并直接根据子键找到父键(例如,不仅是子键的 PK,还有其他值)
    • @ParthManaktala 当然,您可以在存储库中编写自定义查询。例如select c.parent from Child c where c.name = ?1 将检索名称与参数匹配的孩子的父母。
    • 你目前只这样做,只是好奇是否有办法使用 jpa/hibernate 本身来做到这一点。不过还是谢谢!!
    • @ParthManaktala 你能解释一下使用 JPA/Hibernate 本身是什么意思吗?这些查询是用 JPQL 编写的,它代表 JPA 查询语言(因此,它是 JPA/Hibernate 的一部分)。
    猜你喜欢
    • 2018-02-12
    • 2023-03-20
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 2016-05-13
    • 2021-08-14
    • 2017-01-03
    • 1970-01-01
    相关资源
    最近更新 更多