Kotlin Exposed - Auto-create entity object from query result without mapping

42 Views Asked by At

I'm trying to run a query and get an object back with Kotlin exposed and Spring Boot 2 - My code looks like this:

    @Transactional
    fun getClassroomByName(name: String): ClassroomDTO? {
        return Classrooms.select(Op.build {Classrooms.name eq name}).map {
            ClassroomDTO(it[Classrooms.id].value, it[Classrooms.name])
        }.first()
    }

Now, this works fine, but is there a way to create a Classroom object from the results so I can just call classroomObject.toDto() instead of doing it manually here?

class Classroom(id: EntityID<Int>) : IntEntity(id) {
    companion object : IntEntityClass<Classroom>(Classrooms)

    var name by Classrooms.name
    override fun toString(): String {
        return "Classroom(id=$id, name='$name')"
    }

    fun toDto(): ClassroomDTO {
        return ClassroomDTO(id.value, name)
    }

    fun update(classroomDTO: ClassroomDTO){
        name = classroomDTO.name
    }
}

Can I tell kotlin to run the query and get me a list of objects back, like I do here?

    @Transactional
    fun getClassroomById(id: Int): ClassroomDTO? {
        return Classroom.findById(id)?.toDto()
    }
0

There are 0 best solutions below