在 Spring Data Jpa 中使用 DTO 的基于类的投影不起作用

Bil*_*l T 5 spring-mvc spring-data-jpa spring-data-rest spring-boot

在我的 Spring Boot 应用程序中,我尝试使用 DTO 实现基于类的投影,如下所述:

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections.dtos

我有一个域类,如下所示:

@Entity
@Table(name="metadatavalue")
public class MetadataValue {

    @Id
    @Column(name="metadata_value_id")
    private Integer metadataValueId;

    @Column(name="resource_id", insertable=false, updatable=false)
    private Integer resourceId;

    @Column(name="metadata_field_id", insertable=false, updatable=false)
    private Integer metadataFieldId;

    @Column(name="text_value")
    private String textValue;
Run Code Online (Sandbox Code Playgroud)

接下来是更多的类成员、getter 和 setter 等。

我还有一个简单的 DTO 类,其中有一名成员:

public class MetadataDTO {

    private String textValue;

    public MetadataDTO(String textValue) {
        this.textValue = textValue;
    }

    public String getTextValue() {
        return textValue;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的存储库类是:

public interface MetadataValueRepository extends CrudRepository<MetadataValue, Integer> {

    @Query("SELECT m from MetadataValue m WHERE m.handle.handle = :handle AND m.resourceTypeId=m.handle.resourceTypeId")
    List<MetadataValue> findAllByHandle(@Param("handle") String handle);


    @Query("SELECT new path.to.my.package.domain.MetadataDTO(m.textValue AS textValue) FROM MetadataValue m "
            + "WHERE m.handle.handle = :handle AND m.resourceTypeId=m.handle.resourceTypeId")
    List<MetadataDTO> findAllByHandleDTO(@Param("handle") String handle);
}
Run Code Online (Sandbox Code Playgroud)

第一个方法 findAllByHandle 按预期工作,但是当运行第二个方法 findAllByHandleDTO(我希望返回投影)时,我的应用程序抛出错误:

java.lang.IllegalArgumentException: Couldn't find PersistentEntity for type class path.to.my.package.domain.MetadataDTO!
Run Code Online (Sandbox Code Playgroud)

我也尝试从 JpaRepository 进行扩展,结果相同。在另一次尝试中,我尝试使用基于接口的投影,这导致了几乎相同的堆栈跟踪,并用内部类代替了我的类。

我的项目是 spring-boot 2.3.0,带有 Spring Web、Spring Data JPA、Rest Repositories 和 PostgreSQL Driver。

有人可以帮助我了解我做错了什么并让我走上正确的方向吗?

非常感谢!

关于这个问题的更新:(我添加了标签 spring-data-rest)。通过实验,我了解到我可以成功调用我的方法,例如,在我的应用程序类的 run() 方法中。仅当我将该方法作为休息端点调用时,我才会看到错误。这仅仅是与 Spring Data Rest 不兼容的问题吗?