In my repository class, I am doing a native query using the @Query annotiation, by only selecting a few fields from MyDomain like this:
@Repository
public interface MyRepository extends JpaRepository<MyDomain, Long> {
@Query("SELECT q.firstname, q.lastname from MyDomain q WHERE q.firstname = :firstname")
Page<MyDomain> findByFirstName(String firstname, Pageable pageable);
}
Here is the mapper to convert from MyDomain to Dto and vice versa
@Mapper(componentModel = "spring")
public interface Mapper {
MyDomainDto toDto(MyDomain data);
MyDomain fromDto(MyDomainDto data);
}
And then I call this method here in the service:
private ResponseEntity<List<MyDomainDto>> getByFirstName(String firstname, Pageable pageable) {
Page<MyDomain> page = dataRepository.findByfirstName(firstname, pageable);
List<MyDomain> result = page.getContent();
return new ResponseEntity<>(
result.stream().map(mapper::toDto).collect(Collectors.toList()), HttpStatus.OK);
When I fetch the result Page<MyDomain> page = dataRepository.findByfirstName(firstname, pageable); it returns a list of Objects instead of my custom class MyDomain.
If I however use the native query like this, by fetching all the data from MyDomain
@Repository
public interface MyRepository extends JpaRepository<MyDomain, Long> {
@Query("SELECT q from MyDomain q WHERE q.firstname = :firstname")
Page<MyDomain> findByFirstName(String firstname, Pageable pageable);
}
Then I will get the custom class MyDomain returned by Page<MyDomain> page = dataRepository.findByfirstName(firstname, pageable);
How can I achive the same result when I only fetches a few fields instead of all fields? I tried casting it to MyDomain but no success. Thanks in advance (if anyone is reading this on Saturday)