Reputation: 1658
I'm trying to get object of custom type from JPA Repository
VisitRepository.java
@Repository
public interface VisitRepository extends JpaRepository<Visit, Long>, JpaSpecificationExecutor<Visit> {
@Query(value = "select client_id , count(*) from visit where (DATE(jhi_date) between :startDate and :endDate) group by client_id",nativeQuery = true)
List<IIntegerReportData> findByDate(@Param("startDate") String startDate, @Param("endDate") String endDate);
IIntegerReportData.java
package com.mycompany.hiptest.repository;
public interface IIntegerReportData {
Long getId();
Integer getValue();
}
ClientRating.java
public List<ClientsRatingDTO> findAllSorted(String startDate, String endDate, Long fieldNum) {
List<IIntegerReportData> visitReport = visitRepository.findByDate(startDate, endDate);
log.debug("visitReport:" + visitReport.size());
for (IIntegerReportData visit : visitReport
) {
log.debug("value: " + visit.getValue());
}
In debug i get visitReport.size() = 27 (that is correct records count), but
visit.getValue() is NULL for each rows, although there are not null values in this field for each rows.
What's wrong?
Upvotes: 2
Views: 6041
Reputation: 6018
When returning a custom object from a native query, the result column names must match the names of the custom interface, otherwise they'll just have null
values. E.g.:
@Repository
public interface MyRepository extends JpaRepository<MyEntity, Long> {
@Query(value = "SELECT "\"id\" FROM \"my_entity\"", nativeQuery = true)
List<IdNative> findAllIdNative();
interface IdNative {
Long getEntityId();
}
}
Here, getEntityId()
will always return null
because the result table of the query has no entityId
column. To fix, either change the query to match the method:
SELECT "id" AS "entityId" FROM "my_entity"
Or, change the interface method to match the column name:
Long getId();
Upvotes: 1
Reputation: 1292
You could use NativeQuery Annotation:
Have a look at:
https://www.baeldung.com/spring-data-jpa-query
Upvotes: 1