Could any one tell me the real reason of spring-data projection in my case?

Viewed 11856

The case is: I have a repository and two methods, one of them looks like:

//There is no warning about: Activity domain type or valid projection interface expected here...
@Query("select distinct a.creatorId from Activity a")
Optional<List<String>> findAllCreatorIds();

The second method looks like:

//There i have warning about: Activity domain type or valid projection interface expected here
@Query("select distinct a.creatorId from Activity a join a.categories c where c.name in ?1")
Optional<List<String>> findAllCreatorIdsByCategoryNames(Set<String> categoryNames);

It looks workable and tests are passed and the generated query is the following:

SELECT DISTINCT activity0_.created_by AS col_0_0_
FROM activities activity0_
INNER JOIN category_item categories1_ ON 
activity0_.id=categories1_.activity_id
INNER JOIN categories category2_ ON 
categories1_.category_id=category2_.id
WHERE category2_.name IN (?)

I have made the changes to use projection interface. The simple projection interface is:

public interface CreatorIdProjection {
    String getCreatorId();
}

The query was changed:

@Query("select a from Activity a join a.categories c where c.name in ?1")
Optional<List<CreatorIdProjection>> findAllCreatorIdsByCategoryNames(Set<String> categoryNames);

Works too. And here is the generated query:

SELECT activity0_.id AS id1_0_,
       activity0_.price AS price2_0_,
       activity0_.created_by AS created_3_0_,
       activity0_.expiration_date AS expirati4_0_,
       activity0_.insertts AS insertts5_0_,
       activity0_.name AS name6_0_,
       activity0_.start_date AS start_da7_0_,
       activity0_.updatets AS updatets8_0_
FROM activities activity0_
INNER JOIN category_item categories1_ ON activity0_.id=categories1_.activity_id
INNER JOIN categories category2_ ON categories1_.category_id=category2_.id
WHERE category2_.name IN (?)

I have a few questions related to this case:

  1. Why there is no warning for the first method ?

  2. Why the query have a lot of fields after SELECT when we use projection? (to be more precise - why we cannot use "select a.creatorId from Activity a...")

  3. What is the reason of the warning "...domain type or valid projection interface expected here" if as a result we have a query that querying the table data instead of what we need.

2 Answers
Related