am new to JPA and springboot unable to get the api response when am using @Query param(I try achieve the inner join)
Repositoty class:
@Transactional(rollbackFor = Exception.class) @Modifying @Query("select A.id, A.position ,A.title,A.shortdescription,A.thumbnailimage, A.linkactions, A.last_updated_date, A.last_updated_by, B.countryName " + "from ContentManage as A inner join Country as B on A.countryid=B.countryId") List<ContentManage> fetchDataInnerJoin();
Service class:
public ContentManageListResponse queryAllActions() { List<ContentManage> contentManageList = contentManageRepository.fetchDataInnerJoin(); List<ContentManageVO> contentManageVOList = new ArrayList<>(); for (ContentManage contentManage : contentManageList) { ContentManageVO contentManageVO = new ContentManageVO(); BeanUtils.copyProperties(contentManage,contentManageVO); contentManageVOList.add(contentManageVO); } return ContentManageListResponse.builder().contents(contentManageVOList).build(); }
am getting the ” [Ljava.lang.Object; cannot be cast ” exception after that I have changed to as below:
service class
public ContentManageListResponse queryAllActions() { List<ContentManage> contentManageList = contentManageRepository.fetchDataInnerJoin(); List<ContentManageVO> contentManageVOList = new ArrayList<>(); for (Object contentManage : contentManageList) { ContentManageVO contentManageVO = new ContentManageVO(); BeanUtils.copyProperties(contentManage,contentManageVO); contentManageVOList.add(contentManageVO); } return ContentManageListResponse.builder().contents(contentManageVOList).build(); }
foreach added the Object but for the above code am getting null values BeanUtils.copyProperties
is not working
please any one suggest how to fix this.
Advertisement
Answer
Your statement
@Query("select A.id, A.position ,A.title,A.shortdescription,A.thumbnailimage, A.linkactions, A.last_updated_date, A.last_updated_by, B.countryName " + "from ContentManage as A inner join Country as B on A.countryid=B.countryId")
contains parts from ContentManage
and Country
in select.
But your result is only a List<ContentManage>
To solve this you can create a new Dto class containing all the fields from A and from B you need. This Dto class must have an all-args constructor. Then instead of
"select A.id, A.position ,A.title,A.shortdescription,A.thumbnailimage, A.linkactions, A.last_updated_date, A.last_updated_by, B.countryName " + "from ContentManage as A inner join Country as B on A.countryid=B.countryId"
you can write:
"select new com.you.package.YourDtoClass (A.id, A.position ,A.title,A.shortdescription,A.thumbnailimage, A.linkactions, A.last_updated_date, A.last_updated_by, B.countryName) " + "from ContentManage as A inner join Country as B on A.countryid=B.countryId"