Spring Data JPA-返回对象的最佳方法? [英] Spring data jpa - the best way to return object?

查看:320
本文介绍了Spring Data JPA-返回对象的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的对象:

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

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

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

now I would like to get only topics and ids. Is there way to get it in format like this:

[
{
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和主题的对象数组的数组.最好的方法是什么?

I don't like array of arrays I would like to get array of object with property id and topic. What is the nicest way to achieve that?

推荐答案

在Spring Data JPA中,您可以使用

In Spring Data JPA you can use projections:

基于接口的:

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

基于类(DTO):

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

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

Then create a simple query method in your repo:

public interface DocumentationRecordRepository extends CrudRepository<DocumentationRecord, Long> {

    List<IdAndTopic> findBy();
}

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

You can create even dynamic query method:

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

然后像这样使用它:

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

这篇关于Spring Data JPA-返回对象的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆