Osk*_*iak 0 spring hibernate jpa jpql spring-data-jpa
我有这样的对象:
@Entity
public class DocumentationRecord {
@Id
@GeneratedValue
private long id;
private String topic;
private boolean isParent;
@OneToMany
private List<DocumentationRecord> children;
...
}
Run Code Online (Sandbox Code Playgroud)
现在我想只获得主题和ID.有没有办法得到这样的格式:
[
{
id: 4234234,
topic: "fsdfsdf"
},...
]
Run Code Online (Sandbox Code Playgroud)
因为即使只使用此查询
public interface DocumentationRecordRepository extends CrudRepository<DocumentationRecord, Long> {
@Query("SELECT d.topic as topic, d.id as id FROM DocumentationRecord d")
List<DocumentationRecord> getAllTopics();
}
Run Code Online (Sandbox Code Playgroud)
我只能得到这样的记录:
[
[
"youngChild topic",
317
],
[
"oldChild topic",
318
],
[
"child topic",
319
],
]
Run Code Online (Sandbox Code Playgroud)
我不喜欢数组数组我想获得具有属性id和主题的对象数组.实现这一目标最好的方法是什么?
在Spring Data JPA中,您可以使用投影:
基于接口:
public interface IdAndTopic {
Long getId();
String getTopic();
}
Run Code Online (Sandbox Code Playgroud)
基于班级(DTO):
@Value // Lombok annotation
public class IdAndTopic {
Long id;
String topic;
}
Run Code Online (Sandbox Code Playgroud)
然后在repo中创建一个简单的查询方法:
public interface DocumentationRecordRepository extends CrudRepository<DocumentationRecord, Long> {
List<IdAndTopic> findBy();
}
Run Code Online (Sandbox Code Playgroud)
您甚至可以创建动态查询方法:
List<T> findBy(Class<T> type);
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
List<DocumentationRecord> records = findBy(DocumentationRecord.class);
List<IdAndTopic> idAndTopics = findBy(IdAndTopic.class);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1892 次 |
| 最近记录: |