[英]Spring data jpa - the best way to return object?
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. 现在我只想获取主题和ID。 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. 我不希望获得具有属性ID和主题的对象数组。 What is the nicest way to achieve that?
实现这一目标的最好方法是什么?
In Spring Data JPA you can use projections : 在Spring Data JPA中,您可以使用投影 :
Interface based : 基于接口 :
public interface IdAndTopic {
Long getId();
String getTopic();
}
Class based (DTO): 基于类 (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);
You can create a class with attributes id and topic and use constructor injection into query. 您可以创建一个具有id和topic属性的类,并在查询中使用构造函数注入。 Sth like below
像下面这样
@Query("SELECT NEW your.package.SomeObject(d.id, d.topic) FROM DocumentationRecord d")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.