0

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)

1 Answer 1

1

You can achieve it with fetching your data directly to DTO.

If your DTO class looks like this:

package com.your.project;

public class MyDomainDto {
    private String firstname;
    private String lastname;
    
    public MyDomainDto(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }
}

then you can do it in your repository as follows:

@Repository
public interface MyRepository extends JpaRepository<MyDomain, Long> {
    @Query("SELECT new com.your.project.MyDomainDto(q.firstname, q.lastname) from MyDomain q WHERE q.firstname = :firstname")
    Page<MyDomainDto> findByFirstName(String firstname, Pageable pageable);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.