【发布时间】:2017-10-23 04:39:24
【问题描述】:
案例是: 我有一个存储库和两个方法,其中一个看起来像:
//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.creatorId 来自 Activity a...")
警告“...域类型或有效的原因是什么? 此处应有投影界面”,如果结果我们有一个查询 查询表数据而不是我们需要的。
【问题讨论】:
-
为什么要返回 Option
- > ? Optional 无论如何都不应该为空。
-
@JensSchauder,谢谢,我的错,结果集不会为空。我已经删除了 Optional 包装器,但是关于投影的图片是一样的。
-
我无法重现警告。另外我在源代码中找不到警告。您能否提供完整的日志文件行,其中应包括类,可能还包括该日志语句的来源行。您使用的 Spring Data 版本也不错。
-
@JensSchauder,首先感谢您的回复。没有理由提供日志文件,我认为您完全正确,此警告与 Spring Data 框架无关,我检测到此警告是由我正在使用的 ide 产生的,我将联系开发人员或其他人一个来自支持澄清。
标签: java spring-boot spring-data hql h2