JPA 将本机查询结果映射到非实体 DTO

JPA mapping native query result to non entity DTO

我有一个复杂的本机查询,我正在尝试将其结果映射到非实体 DTO class。我正在尝试将 JPASqlResultSetMappingConstructorResult

一起使用

我的 DTO class

@Data
public class Dto {

    private Long id;

    private String serial;

    private Long entry;

    private int numOfTasks;
}

我的实体 class,它具有我将称之为本机查询结果的存储库接口。

@SqlResultSetMapping(
        name = "itemDetailsMapping",
        classes = {
                @ConstructorResult(
                        targetClass = Dto.class,
                        columns = {
                                @ColumnResult(name = "ID"),
                                @ColumnResult(name = "SERIAL"),
                                @ColumnResult(name = "ENTRY"),
                                @ColumnResult(name = "TASKS")
                        }
                )
        }
)

@NamedNativeQuery(name = "getItemDetails", query = "complex query is here", resultSetMapping = "itemDetailsMapping")
@Entity
@Data
public class Item {}

存储库

@Repository
public interface ItemRepository extends JpaRepository<Item, Long> {

    ...     

    List<Dto> getItemDetails();

}

当我从 ItemRepository 调用 getItemDetails() 时,出现以下错误:

org.springframework.data.mapping.PropertyReferenceException: No property itemDetails found for type Item

SqlResultSetMappingConstructorResult 的正确使用方法是什么 并解决这个问题。

如有任何帮助,我们将不胜感激。

要使用命名查询,命名查询的名称必须以实体名称作为前缀:

@NamedNativeQuery(name = "Item.getItemDetails", 
                 query = "complex query is here", resultSetMapping = "itemDetailsMapping")

那么接口方法必须与命名查询同名,不带前缀:

List<Dto> getItemDetails();

-

在参考文档中阅读有关 Spring Data JPA 和命名查询的更多信息 https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.named-queries