Spring 数据 jpa - return 对象的最佳方式?

Spring data jpa - the best way to return object?

我有这样的对象:

@Entity
public class DocumentationRecord {
    @Id
    @GeneratedValue
    private long id;

    private String topic;
    private boolean isParent;
    @OneToMany
    private List<DocumentationRecord> children;
...
}

现在我只想获取主题和 ID。有没有办法以这样的格式获取它:

[
{
id: 4234234,
topic: "fsdfsdf"
},...
]

因为即使只使用这个查询

public interface DocumentationRecordRepository extends CrudRepository<DocumentationRecord, Long> {

    @Query("SELECT d.topic as topic, d.id as id FROM DocumentationRecord d")
    List<DocumentationRecord> getAllTopics();
}

我只能得到这样的记录:

[
  [
    "youngChild topic",
    317
  ],
  [
    "oldChild topic",
    318
  ],
  [
    "child topic",
    319
  ],
]

我不喜欢数组数组 我想获得具有 属性 ID 和主题的对象数组。实现该目标的最佳方法是什么?

您可以创建具有属性 id 和主题的 class 并使用构造函数注入到查询中。像下面这样

@Query("SELECT NEW your.package.SomeObject(d.id, d.topic) FROM DocumentationRecord d")

在 Spring Data JPA 中你可以使用 projections:

基于接口

public interface IdAndTopic {
    Long getId();
    String getTopic();
}

Class 基于 (DTO):

@Value // Lombok annotation
public class IdAndTopic {
   Long id;
   String topic;
}

然后在您的存储库中创建一个简单的查询方法:

public interface DocumentationRecordRepository extends CrudRepository<DocumentationRecord, Long> {

    List<IdAndTopic> findBy();
}

甚至可以创建动态查询方法:

List<T> findBy(Class<T> type);

然后像这样使用它:

List<DocumentationRecord> records = findBy(DocumentationRecord.class);
List<IdAndTopic> idAndTopics = findBy(IdAndTopic.class);