Best practice for DTO mapping in Kotlin/Spring Boot with ManyToOne/OneToMany
11:43 01 Nov 2024

I'm learning Kotlin in DDD and there is one thing I don't know Currently, I have these two entities :

@Entity
@Table(name = "events")
class EventEntity(
    @Id
    val id: Long?,
    val title: String,
    @OneToMany
    @JoinColumn(name = "event_id")
    val participants: List = ArrayList(),
) {
    fun toEvent() = Event(
        id,
        title,
        participants.map { it.toParticipant() }
    )
}
@Entity
@Table(name = "participants")
class ParticipantEntity(
    @Id
    val id: Long?,
    val lastName: String,
    @ManyToOne
    @JoinColumn(name = "event_id")
    val event: EventEntity,
) {
    fun toParticipant() = Participant(
        id,
        lastName,
    )
} 

and these domain objects

data class Event(
    val id: Long?,
    val title: String,
    val participants: List = ArrayList(),
)
data class Participant(
    val id: Long?,
    val lastName: String,
)

Also, I have some mapping extension functions

// EventRepository
fun Event.toEventEntity() = EventEntity(
    id,
    title,
    participants.toParticipantEntities()
)
// ParticipantRepository
fun Iterable.toParticipantEntities(): List {
    return this.map { it.toParticipantEntity() }
}

fun Participant.toParticipantEntity() = ParticipantEntity(
    id,
    lastName,
)

My problem is that I don't kwow how to avoid No value passed for parameter 'event' in my toParticipantEntity function and how to don't have a cyclic mapping? If someone has an answer or an example on how to, I'll appreciate it! And if you have some tips about that small pieces of code...

Have a good day!

kotlin mapping domain-driven-design