[英]Returning child entities from a parent entity with JPA join
How can I return a list of entities that has a relationship to a parent in JPA? 如何返回与JPA中的父级有关系的实体的列表?
I have a User entity that has a @OneToMany mapping on a property named pets
. 我有一个User实体,该实体在名为
pets
的属性上具有@OneToMany映射。 The child entities are of type Pet. 子实体的类型为Pet。 It is only a uni-directional relationship.
这只是单向关系。
How can I write a join in JPA that returns all pets given a user? 如何在JPA中编写联接以返回给定用户的所有宠物?
So you have a couple of options. 因此,您有两种选择。
You can use the following annotations: 您可以使用以下注释:
@ManyToOne
@JoinColumn
This is how you would use it. 这就是您将如何使用它。
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
}
What essentially happens is the list of pets is populated when you are querying for the user object. 本质上是在查询用户对象时填充了宠物列表。
Using JPA to Query the DB. 使用JPA查询数据库。
So i am guessing that Your user would have some sort of id and the pet table would have some sort of Id to the user that are linked. 因此,我猜测您的用户将具有某种ID,而宠物表将具有与所链接用户的ID。
So we would do the following 因此,我们将执行以下操作
Select * from user where user_id = ?;
this will essentially give you the user object 这实际上将为您提供用户对象
Select * from pet where owner_user_id = ?
this will essentially give you all the pets that belong to that user. 这实际上将为您提供属于该用户的所有宠物。
Then you can populate your object yourself. 然后,您可以自己填充对象。
I am not 100% sure of how your table looks like, but I was hoping to give it a stab from just what I would do point of view. 我不是100%知道您的桌子是什么样子,但是我希望从我的观点出发给它一个机会。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.