首页 > 解决方案 > spring data @query 和 projection 应该只选择需要的字段,但情况并非如此

问题描述

假设我有一个实体(简化)

@Entity
FooEntity {
  long id;
  String name;
  int age;
  boolean deleted;
}

我想使用弹簧投影只选择这个实体的 id 和 name 字段

所以我创建了第一个接口和实现它的类

public interface DictionaryInterface {
    Long getId();
    String getName();
}

@Value
class DictionaryObject implements DictionaryInterface {
   Long id;
   String name;
}

然后我使用使用投影接口的方法创建了存储库接口

<T> List<T> findByDeleted(boolean deleted, <Class<T> type);

并尝试了两次调用并查看了生成的 sql

findByProjection(false, DictionaryInterface.class) 
// here sql select includes all fields even those that were not needed (age field)


findByProjection(false, DictionaryObject.class) -> 
// here sql select includes only id and name fields

我从阅读 spring 数据文档的理解是行为应该是相同的,我必须只选择需要的字段,但我清楚地看到它不起作用

我哪里错了?

标签: javaspringspring-data-jpa

解决方案


推荐阅读