【问题标题】:Returning child entities from a parent entity with JPA join使用 JPA 连接从父实体返回子实体
【发布时间】:2013-08-29 17:19:16
【问题描述】:

如何返回与 JPA 中的父级有关系的实体列表?

我有一个用户实体,它在名为pets 的属性上具有@OneToMany 映射。子实体的类型为 Pet。这只是一个单向的关系。

如何在 JPA 中编写一个返回给定用户的所有宠物的联接?

【问题讨论】:

    标签: java hibernate jpa


    【解决方案1】:

    所以你有几个选择。

    您可以使用以下注释:

    @ManyToOne
    @JoinColumn
    

    这就是你将如何使用它。

    public class User
    {
       // your standard fields / columns in database
    
       @OneToMany  (Fetch can be of eager/ lazy)
       @JoinColumn (name="column to join on", referencedColumnName="column to join on in parent class")
       private List<Pet> pets;
    }
    
    
    public Class Pet
    {
       //data fields
    }
    

    当您查询用户对象时,实际上会填充宠物列表。

    使用 JPA 查询数据库。

    所以我猜测您的用户会有某种 id,而宠物表会有某种与链接的用户相关的 Id。

    所以我们会做以下事情

    Select * from user  where user_id = ?;
    

    这基本上会给你用户对象

    Select * from pet where owner_user_id = ?
    

    这实际上会为您提供属于该用户的所有宠物。

    然后你可以自己填充你的对象。

    我不能 100% 确定您的桌子是什么样子,但我希望从我会做什么的角度来试一试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-23
      • 2021-06-06
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-03
      相关资源
      最近更新 更多