如何转换 spring 数据存储库 return 的对象?

How can transform objects that spring data repositories return?

我看过this 我有类似的问题,但我只想从四个字段中获取两个 - 例如:仅从 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(); 
     //...
 }

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

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

建议您需要使用DTO like here

创建你的 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 
}

然后编辑你的仓库:

public interface CatRepo extends CrudRepository<Cat,Long> {

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

您将获得一份 CatDto 的列表。

...CatDto(...) - 是 CatDto 构造函数的 fully qualified name。例如 com.example.mycatproject.domain.CatDto.

另一种方法是为 DTO 使用“projection”接口:

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(); 
}