In my project, I am using Spring Data JPA and extend the JpaRepository interface for my data fetching class.
OrganizationMaster class :
@Entity
@Table(name="organization_master")
public class OrganizationMaster {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="organization_id")
private int organizationId;
@OneToMany(mappedBy="organizationMaster")
private List<CompanyMaster> companyMasters;
}
CompanyMaster Class:
Entity
@Table(name="company_master")
public class CompanyMaster {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="company_id")
private int companyId;
@ManyToOne
@JoinColumn(name="organization_id")
private OrganizationMaster organizationMaster;
}
My Controller
@RequestMapping(value = "/GetOrganization", method = RequestMethod.GET)
public
@ResponseBody
List<OrganizationMaster> getOrganization(){
return organizationService.getOrganization();
}
OrganizationService:
public interface OrganizationService {
List<OrganizationMaster> getOrganization();
}
OrganizationServiceImpl:
@Service
public class OrganizationServiceImpl implements OrganizationService{
@Autowired
private OrganizationDao organizationDao;
@Override
public List<OrganizationMaster> getOrganization() {
return organizationDao.findAll();
}
}
OrganizationDao Interface:
public interface OrganizationDao extends JpaRepository<OrganizationMaster,Long> {
}
My Output Response is: [{"organizationId":5,"companyMasters":[{"companyId":29},{"companyId":30}]}]
But my need is [{"organizationId":5}]
When I am trying to get data from the organization master using findall() method it also fetches data from the company master based on the relationship. How can I achieve lazy fetching (get data only from organization master) using spring data JpaRepository
System.out.println(organization.getCompanyMasters()), it will load them at that time, because printing a list means printing every element of the list, and to print an element, you need to have that element, and to have that element, you need to load it.