SimBot
SimBot

Reputation: 109

How to specify which fields to return with @query anotation in Spring Data?

When I run the following query using the @query anotation in Spring Boot, it returns the correct result:

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"
        }
    }
}

When I try to specify the fields to return:

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

I get the following error:

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

How do I specify which fields to return with @query annotation in Spring Data?

Upvotes: 0

Views: 179

Answers (2)

Alan Hay
Alan Hay

Reputation: 23226

The suggested link does not fully cover all possibilities.

From the Hopper release of Spring Data it is possible to directly return Projections directly from Query methods:

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

So you can therefore do:

public interface ThingRepository extends JpaRepository<Thing, Long>{

   @Query("select t from Thing t .....")
   public List<ThingProjection> findBySomeCriteria(...);
}

Upvotes: 0

SimBot
SimBot

Reputation: 109

Yes it seems the question that Manish posted the link to has the answer.

Answer: You can't.

Spring data will return the whole entity, not individual fields. You can't make it do that. If you want to do that you have to use projections. See linked post.

Thanks @Manish

Upvotes: 1

Related Questions