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

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

问题描述

我有这样的对象:

@Entity公共类文档记录{@ID@GeneratedValue私人长ID;私人字符串主题;私有布尔值 isParent;@一对多私人列表<DocumentationRecord>孩子们;...}

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

<预><代码>[{编号:4234234,主题:fsdfsdf"},...]

因为即使只使用这个查询

public interface DocumentationRecordRepository extends CrudRepository{@Query("SELECT d.topic 作为主题,d.id 作为 id FROM DocumentationRecord d")列表<文档记录>getAllTopics();}

我只能得到这样的记录:

<预><代码>[["幼儿话题",317],["老子话题",318],[儿童主题",319],]

我不喜欢数组数组我想获取具有属性 id 和主题的对象数组.实现这一目标的最佳方法是什么?

解决方案

在 Spring Data JPA 中你可以使用 投影:

基于界面:

公共接口IdAndTopic {长 getId();字符串 getTopic();}

基于类(DTO):

@Value//龙目岛注解公共类 IdAndTopic {长ID;字符串主题;}

然后在你的 repo 中创建一个简单的查询方法:

public interface DocumentationRecordRepository extends CrudRepository{列表findBy();}

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

ListfindBy(Class type);

然后像这样使用它:

List记录 = findBy(DocumentationRecord.class);列表idAndTopics = findBy(IdAndTopic.class);

I have object like this:

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

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

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

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

Because even using only this query

public interface DocumentationRecordRepository extends CrudRepository<DocumentationRecord, Long> {

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

I was only able to get record like this:

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

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?

解决方案

In Spring Data JPA you can use projections:

Interface based:

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

Class based (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);

Then use it like this:

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

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

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