[英]Spring Data JPA - Best Way to Update Concurrently Accessed "Total" Field
[英]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.