Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

hibernate - 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. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...