[英]How to retrieve parent entity using child entity-Spring data JPA
Here is the DB table structure with one-to-many relation.这是具有一对多关系的数据库表结构。 EMP_DETAILS and MODEL_DETAILS are connected with action_id with a one-to-many relationship.
EMP_DETAILS 和 MODEL_DETAILS 与 action_id 以一对多的关系连接。
Below are the entities create for both child and parent tables.下面是为子表和父表创建的实体。
EmpDetails.java EmpDetails.java
@Table(EMP_DETAILS)
@Entity
public class EmpDetails{
@Id
@Column(name="eid", nullable=false)
private Integer eid;
@OneToMany(cascade=CascadeType.ALL, mappedBy="empDetails"
private Set<ModelDetails> modelDetailsSet;
//other column mappings
}
ModelDetails.java型号详情.java
@Table(MODEL_DETAILS)
@Entity
public class ModelDetails{
@Id
@Column(name="id)
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="eid",referencedColumnName="eid", nullable=false)
private EmpDetails empDetails;
@Column(name="model_name")
private String modelName;
@Column(name="created_on")
private Date createdOn;
//Other column mappings and getters setters
}
The below method does returns me the Model_Details records.下面的方法确实返回了 Model_Details 记录。
List<ModelDetails> modelDetailList=findByModelNameOrderByCreatedOnDesc("Any_Existng_Name");
But when we try to get the parent record related to the child record I get null like below..,但是当我们尝试获取与子记录相关的父记录时,我得到 null 如下所示..,
modelDetailList.get(0).getEmpDetails();//THIS RETURNS NULL!
Any solution for this对此的任何解决方案
@ManyToOne(fetch=FetchType.LAZY)
This is why the parent is null.这就是为什么父级是 null。 You told JPA you don't want to automatically fetch the linked entity.
您告诉 JPA 您不想自动获取链接实体。 This is generally a good thing as you don't want to load extra data that may not be needed all the time.
这通常是一件好事,因为您不想加载可能一直不需要的额外数据。
You could change that to @ManyToOne(fetch=FetchType.EAGER)
if you'll need EmpDetails every time to load ModelDetails.如果您每次都需要 EmpDetails 来加载 ModelDetails,则可以将其更改为
@ManyToOne(fetch=FetchType.EAGER)
。
If you only need the EmpDeatils for this query you'll need to modify findByModelNameOrderByCreatedOnDesc to retrieve the associated entity.如果您只需要此查询的 EmpDeutils,则需要修改 findByModelNameOrderByCreatedOnDesc 以检索关联的实体。
Your query should look something like SELECT md FROM ModelDetails md JOIN FETCH EmpDetails = WHERE md.name =:name ORDER BY createdOn desc
您的查询应该类似于
SELECT md FROM ModelDetails md JOIN FETCH EmpDetails = WHERE md.name =:name ORDER BY createdOn desc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.