簡體   English   中英

Spring Data JPA-返回對象的最佳方法?

[英]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和主題的對象數組。 實現這一目標的最好方法是什么?

在Spring Data JPA中,您可以使用投影

基於接口

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

基於類 (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);

您可以創建一個具有id和topic屬性的類,並在查詢中使用構造函數注入。 像下面這樣

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM