【问题标题】:How to specify which fields to return with @query anotation in Spring Data?如何在 Spring Data 中使用 @query 注解指定返回哪些字段?
【发布时间】:2016-12-19 15:06:42
【问题描述】:

当我在 Spring Boot 中使用 @query 注释运行以下查询时,它会返回正确的结果:

SELECT p FROM Collection p WHERE LOWER(p.description) LIKE LOWER(CONCAT('%',:searchTerm, '%'))

{
    "_embedded": {
        "collections": [
            {
                "place": "Blessington",
                "description": "Collection of old shoes for recycling",
                "_links": {
                    "self": {
                        "href": "http://localhost:8080/collections/1"
                    },
                    "collection": {
                        "href": "http://localhost:8080/collections/1"
                    }
                }
            }
        ]
    },
    "_links": {
        "self": {
            "href": "http://localhost:8080/collections/search/findByDescription?searchTerm=shoe"
        }
    }
}

当我尝试指定要返回的字段时:

SELECT p.description FROM Collection p WHERE LOWER(p.description) LIKE LOWER(CONCAT('%',:searchTerm, '%'))

我收到以下错误:

{
    "cause": null,
    "message": "PersistentEntity must not be null!"
}

如何在 Spring Data 中使用 @query 注解指定返回哪些字段?

【问题讨论】:

标签: spring-data-rest


【解决方案1】:

是的,Manish 发布链接的问题似乎有答案。

回答:你不能。

Spring 数据将返回整个实体,而不是单个字段。你不能让它这样做。如果你想这样做,你必须使用 projections。请参阅链接的帖子。

谢谢@Manish

【讨论】:

    【解决方案2】:

    建议的链接并未完全涵盖所有可能性。

    从 Spring Data 的 Hopper 版本中,可以直接从 Query 方法中直接返回 Projections:

    https://spring.io/blog/2016/05/03/what-s-new-in-spring-data-hopper#projections-on-repository-query-methods

    所以你可以这样做:

    public interface ThingRepository extends JpaRepository<Thing, Long>{
    
       @Query("select t from Thing t .....")
       public List<ThingProjection> findBySomeCriteria(...);
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-11
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 2015-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多