Oskar Woźniak
Oskar Woźniak

Reputation: 715

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?

Upvotes: 1

Views: 4016

Answers (2)

Cepr0
Cepr0

Reputation: 30309

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

Upvotes: 8

soulcoder
soulcoder

Reputation: 301

You can create a class with attributes id and topic and use constructor injection into query. Sth like below

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

Upvotes: 3

Related Questions