Vasia Zaretskyi
Vasia Zaretskyi

Reputation: 347

Retrieve DTO with list inside using JPA

Is there a way to get such object within a single query in JPA?

data class PartcipantsDTO(
   val max: Int,
   val list: List<ParticipantCardDTO>
) // this one

ParticipantCardDTO(
   val id: Long,
   val name: String
)

Assuming that entities looks like:

@Entity
ParticipantEntity(
   @Id id: Long,
   name: String,
   @ManyToOne event: EventEntity
)

@Entity
EventEntity(
   @Id id: Long,
   @OneToMany participants: List<Long>
)

To search by EventEntity id was trying query like:

SELECT new com.***.ParticipantsDTO(
   e.max,
   SELECT new ParticipantCardDTO(
      p.id,
      p.name
   )
)
FROM ParticipantEntity p, EventEntity e
WHERE p.id IN e.participants AND e.id = :id

But it doesn't work

I do know that it can be done with 2 separate queries, but I want to avoid opening 2 connections due to inefficiency

Upvotes: 1

Views: 467

Answers (1)

sajad nouri
sajad nouri

Reputation: 21

you can get ParticipantEntity using JPA, then map it and its participants list to DTO in Java, hibernate will handle its properties.

this is because hibernate have cache and handles performance issues itself.

Upvotes: 1

Related Questions