Spring数据jpa - 返回对象的最佳方法?

时间:2017-10-22 19:30:30

标签: spring hibernate jpa spring-data-jpa jpql

我有这样的对象:

@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和主题的对象数组。实现这一目标最好的方法是什么?

2 个答案:

答案 0 :(得分:6)

在Spring Data JPA中,您可以使用projections

基于界面

print unicode('\xff\xaa', 'utf-8', errors='replace')

基于类(DTO):

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

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

@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);

答案 1 :(得分:2)

您可以使用属性id和topic创建一个类,并使用构造函数注入到查询中。 ......如下所示

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