简体   繁体   English

Spring Data JPA和Projection获得TupleConverter的ConverterNotFoundException

[英]Spring Data JPA and Projection getting ConverterNotFoundException for TupleConverter

Is there a way to write and register a TupleConverter converter in Spring Data? 有没有一种方法可以在Spring Data中编写和注册TupleConverter转换器? I'm getting this exception when I have an @Query annotation in the Repository interface and asking for Projection. 当我在Repository接口中具有@Query批注并要求进行投影时,出现此异常。

The Interface: 接口:

public interface ProjectRepository extends JpaRepository<Project, Integer> {
    @Query("select p.projectId, p.projectName, p.techstack from Project p")
    public List<ProjectItem> findAllForTest();
}

The DTO: DTO:

public class ProjectItem {
    private final Integer projectId;
    private final String projectName;
    private final String techstack;
    @JsonCreator
    public ProjectItem(
        @JsonProperty("projectId") Integer projectId, 
        @JsonProperty("projectName") String projectName, 
        @JsonProperty("techstack") String techstack
    ) {
        this.projectId = projectId;
        this.projectName = projectName;
        this.techstack = techstack;
    }
    public Integer getProjectId() {
        return projectId;
    }
    public String getProjectName() {
        return projectName;
    }
    public String getTechstack() {
        return techstack;
    }
}

The exception 例外

No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [project.item.ProjectItem]] with root cause 找不到能够从根本原因将[org.springframework.data.jpa.repository.query.AbstractJpaQuery $ TupleConverter $ TupleBackedMap]类型转换为[project.item.ProjectItem]]类型的转换器

使用JPQL构造函数表达式

@Query("select new com.company.path.to.ProjectItem(p.projectId, p.projectName, p.techstack) from Project p")

You're close. 你近了 If you just want a DTO with a few of the items from the original item, just use the interface projection technique with methods having the same signatures as the Project class method items you want: 如果您只希望DTO包含原始项目中的一些项目,则只需将接口投影技术与具有与所需的Project类方法项目相同的签名的方法一起使用:

public interface ProjectTestSummary {
    public Integer getProjectId();
    public String getProjectName();
    public String getTechstack();
}

And in your DAO: 在您的DAO中:

public interface ProjectRepository extends JpaRepository<Project, Integer> {
    public List<ProjectTestSummary> findAllProjectedBy();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM