Reputation: 235
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.
Below are the entities create for both child and parent tables.
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
@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.
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..,
modelDetailList.get(0).getEmpDetails();//THIS RETURNS NULL!
Any solution for this
Upvotes: 1
Views: 4404
Reputation: 46
@ManyToOne(fetch=FetchType.LAZY)
This is why the parent is null. You told JPA you don't want to automatically fetch the linked entity. 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.
If you only need the EmpDeatils for this query you'll need to modify findByModelNameOrderByCreatedOnDesc to retrieve the associated entity.
Your query should look something like SELECT md FROM ModelDetails md JOIN FETCH EmpDetails = WHERE md.name = :name ORDER BY createdOn desc
Upvotes: 3