I have a interface
implementing JPARepository
and have three methods, one of them is having a custom @Query
.
public interface PersonRepository extends JpaRepository<Person, Long> {
List<Person> getPersonBycountryCode(String countryCode);
List<Person> findByCountryCodeAndCity(String string,String city);
@Query(value = "SELECT person.firstName as firstName, person.lastName as lastName, person.countryCode as country, person.city as city,"
+ " SQRT(POWER((69.1 * (person.age - :age )) , 2 )"
+ " + POWER((53 * (person.experience - :experience )), 2)) as eligibility"
+ " FROM Person person"
+ " ORDER BY eligibility ASC")
List<PersonDetailsDto> findPersonDetailsByEligibility(
@Param("age") BigDecimal age,
@Param("experience") BigDecimal experience,
Pageable pageable
);
}
Problem is: method with @Query
does not return list of PersonDetailsDto
but return list of list of strings (List<List<String>>
).
PersonDetailsDto
is a POJO class with all the variables described in a query output (firstName, lastName, country, city, eligibility) and also a constructor with all the variables as Parameters. Other two methods does return list of Person object.
Any idea?
Actually JpaRepository<Person, Long>
means that, you can use only Person as your dto in jpa repository methods.
For your solution you can just define your dto interface inside the repository :
public interface PersonRepository extends JpaRepository<Person, Long> {
List<Person> getPersonBycountryCode(String countryCode);
List<Person> findByCountryCodeAndCity(String string,String city);
@Query(value = "SELECT person.firstName as firstName, person.lastName as lastName, person.countryCode as country, person.city as city,"
+ " SQRT(POWER((69.1 * (person.age - :age )) , 2 )"
+ " + POWER((53 * (person.experience - :experience )), 2)) as eligibility"
+ " FROM Person person"
+ " ORDER BY eligibility ASC")
List<PersonDetailsDto> findPersonDetailsByEligibility(
@Param("age") BigDecimal age,
@Param("experience") BigDecimal experience,
Pageable pageable
);
//define the interface here
public interface PersonDetailsDto{
public String getFirstName();
public String getLastName();
public String getCountry();
public String getCity();
public Integer getEligibility();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With