Flora
Flora

Reputation: 563

How can transform objects that spring data repositories return?

I have seen this and I have similar problem, but I would like to get only two from four fields - for example: only id and name from id, name, dateOfBirth, weight.

 public interface ICatDAO extends CrudRepository<Cat,Long> {

     @Query(value = "SELECT c.id, c.name FROM Cat c")
     public List<Cat> findAll(); 
     //...
 }

If I use query: @Query(value = "SELECT c FROM Cat c") I get objects list type 'Cat', but with all fields.

If I use query: @Query(value = "SELECT c.id, c.name FROM Cat c") I get object list type 'Object' and this is the problem. What should I do in this case?

Upvotes: 2

Views: 1772

Answers (1)

Cepr0
Cepr0

Reputation: 30439

You need to use DTO like here is suggested.

Create your CatDto:

public class CatDto {
    private Long id;
    private String name;

    public CatDto(Long id, String name) {
        this.id = id;
        this.name = name;
    }
    // getters, setters and other stuff you need 
}

Then edit you repo:

public interface CatRepo extends CrudRepository<Cat,Long> {

    //...
    @Query("select new ...CatDto(c.id, c.name) from Cat c")
    public List<CatDto> getCatDtos(); 
}

And you will get a list of your CatDto.

...CatDto(...) - is a fully qualified name of your CatDto constructor. For examlpe com.example.mycatproject.domain.CatDto.

Another approach is to use 'projection' interface for DTO:

public interface CatDto {
    Long getId();
    String getName();
}

public interface CatRepo extends CrudRepository<Cat,Long> {

    //...
    @Query("select c.id as id, c.name as name from Cat c")
    public List<CatDto> getCatDtos(); 
}

Upvotes: 5

Related Questions