有人能告诉我在我的情况下弹簧数据投影的真正原因吗?
情况是:我有一个存储库和两种方法,其中一个看起来像:
//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();
第二种方法如下所示:
//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);
它看起来可行,并且通过了测试,生成的查询如下:
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 (?)
我已进行更改以使用投影界面。简单的投影接口是:
public interface CreatorIdProjection {
String getCreatorId();
}
查询已更改:
@Query("select a from Activity a join a.categories c where c.name in ?1")
Optional<List<CreatorIdProjection>> findAllCreatorIdsByCategoryNames(Set<String> categoryNames);
也有效。下面是生成的查询:
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 (?)
我有一些与此案例相关的问题:
为什么第一种方法没有警告?
为什么当我们使用投影时,查询在 SELECT 之后有很多字段?(更准确地说 - 为什么我们不能使用“从活动a中选择a.creatorId...”)
警告“...此处期望的域类型或有效投影接口“,如果因此我们有一个查询,查询表数据而不是我们需要的数据。