Issue
I am querying a view which joins three tables and returns the result like below:
select * from v_project_details
Project_ID Repo_Name Branch_Name
100 Repo1 Branch1
100 Repo1 Branch2
101 Repo2 Branch2
@Getter
@Setter
@Entity
@Table(name='v_project_details')
public class ProjectDetails{
@Id
@Column(name="Project_Id")
private int ProjectId
}
@Column(name="Repo_Name")
private String RepoName
}
@Column(name="Branch_Name")
private String BranchName
}
@Query(select p from v_project_details p)
List<ProjectDetails> findAll();
Results:
Project_ID Repo_Name Branch_Name
100 Repo1 Branch1
100 Repo1 Branch1 - I am expecting Branch2 here
101 Repo2 Branch2
when i query the table from spring jpa, i see three results but first row is repeated twice.
Looks like hibernate is not reinstantiating the object if @Id value is repeated more than once in the result set.
How do i force it to reinstantiate the object ? I do not have an unique identifier in the view as my view is joined from different tables.
Solution
@Id
is used by JPA to identify the primary key. In your case, project_id
as your primary key, which JPA understands that both row1 and row2 as same records. If project_id
is not your unique identifier for your records but instead a combination of multiple fields like (eg: combination of project_id
, repo_name
and branch_name
), you need to define a composite primary key based on those 3 fields. refer to below post by baledung to know more on composite primary keys.
Composite primary keys with JPA
Answered By - mike