如何转换 Spring 数据存储库返回的对象?

Dam*_*ris 2 java spring jpql spring-data spring-data-jpa

我已经看到这个 并且我有类似的问题,但我只想从四个字段中获取两个 - 例如:仅从 id、name、dateOfBirth、weight 中获取 id 和 name。

 public interface ICatDAO extends CrudRepository<Cat,Long> {

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

如果我使用查询:@Query(value = "SELECT c FROM Cat c")我会得到对象列表类型“Cat”,但包含所有字段。

如果我使用查询:@Query(value = "SELECT c.id, c.name FROM Cat c")我得到对象列表类型“对象”,这就是问题所在。这种情况我该怎么办?

Cep*_*pr0 5

您需要像这里建议的那样使用DTO 。

创建您的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 
}
Run Code Online (Sandbox Code Playgroud)

然后编辑您的存储库:

public interface CatRepo extends CrudRepository<Cat,Long> {

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

您将获得您的CatDto.

...CatDto(...)- 是构造函数的完全限定名称CatDto。例如com.example.mycatproject.domain.CatDto

另一种方法是使用DTO 的“投影”接口:

public interface CatRepo extends CrudRepository<Cat,Long> {

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