Load several JPA entities using Kotlin coroutine

kotlin jpa
no default constructor for entity kotlin
kotlin-jpa embeddable
kotlin-jpa dsl
kotlin dto
kotlin no-arg constructor
hibernate validator kotlin
kotlin jpa manytoone

I am trying to load several entities using Hibernate and Kotlin coroutine in application layer. Doing something like this.

fun load() : SomeData {

    val steps = someFunctionCallToGetSteps()

    val stepCollection : List<Step> = MutableList()

    runBlocking {

        for (step in steps) {

            val s = async { getStepData(step) }
            payers.add(s.await())
        }
    }
}

private suspend fun getStepData(step : Int) : Iterable<Step> {

    return someComputation()
}

But this approach is not correct because I am using await immediately so its not async per sé. I was told to collect all deferreds and use awaitAll but I cannot find any example of it anywhere. Can this be done?

Take every s into a list and outside of for loop do awaitAll(yourListOfs)

Using Kotlin with JPA / Hibernate : Kotlin, For those using Kotlin with Spring and JPA projects are you favoring classes or taking the more traditional approach by creating mutable entities, the null @​Column(name = "name") lateinit var name: String @OneToMany(fetch We believe an API written from the ground up in Kotlin with coroutines can Many Thanks! One might think that data classes are perfect to map database entities, and they are actually very good, but you will to think a little more in order to use them correctly with JPA. Data classes automatically implement toString() , equals() and hashCode() based on the properties defined in the primary constructor.

If I get it right you need something like this to accomplish your goal. Call multiple async builders and then map Deferred to Steps. Rather that using Dispatchers.Default it would be better to create your own dispatcher.

data class Step(val step: Int)

fun main(args: Array<String>) = runBlocking {

    val steps = someFunctionCallToGetSteps()

    val result = coroutineScope {
        val defferedSteps = steps.map {
            async(Dispatchers.Default) {
                getStepData(it)
            }
        }
        defferedSteps.map { deferred -> deferred.await() }
    }

    for (step in result)
        println(step)
}

fun someFunctionCallToGetSteps(): List<Int> {
    return listOf<Int>(1, 2, 3, 4)
}

suspend fun getStepData(step: Int): Step {
    println("[${Thread.currentThread().name}] loading...")
    delay(500)
    return Step(step)
}

Kotlin for Enterprise Applications using Java EE: Develop, test, , JPA entities cascading 146 data sources 150 join column, naming 147 ManyToOne Kotlin code adding, in Java project 70, 71, 73 Kotlin plugins all-​open compiler plugin 80 11 configuring, in Eclipse 59, 60, 62, 63 configuring, in project 54 coroutines 63, 66, 68, list iterating over 28, 29 Load Balancer 250 M Mac. IntelliJ IDEA 2018.3 comes with better JPA and Spring Data support for Kotlin. The IDE can automatically inject JPQL into query strings, providing completion for entity names and parameters: Named queries are also supported: Spring Data interfaces can now also be written in Kotlin, and IntelliJ IDEA will understand the entities you use.

Finally I was able to solve this issue. I am posting answer with a hope that other might benefit from it.

fun load() : List<Result> {

    val steps = someFunctionCallToGetSteps()
    val result: List<Result> = ... 

    runBlocking {

        val stepsDeferred = steps.map { async { getStepData(it) } }

        stepsDeferred.awaitAll().forEach { result.add(it) }
    }

    return result
}

private suspend fun getStepData(step : Int) : Iterable<Step> {

    return someComputation()
}

Spring Boot: A bit more cool with Kotlin, In the context of my favorite framework, Spring Boot, I have recently The example contains: a JPA entity, a JPA repository, a REST Also, getMessages uses the Kotlin 1.1 experimental “coroutine” functionality [kotlin-coroutines]. MessageClient @Test fun `getMessages() should fetch messages in  Every coroutine has a job, and you can use the job to cancel the coroutine. Jobs can be arranged into parent-child hierarchies. Canceling a parent job immediately cancels all the job's children, which is a lot more convenient than canceling each coroutine manually.

Mapping JPA entities with Kotlin, Data classes automatically implement toString() , equals() and hashCode() based on the properties defined in the primary constructor. Because of  By using our site, Ilya Rodionov. Apparently, this user prefers to keep an air of mystery about them. 0 Load several JPA entities using Kotlin coroutine Dec

Best Performance Practices for Hibernate 5 and Spring Boot 2 (Part , Item 81: How to Load Multiple Entities by Id via Specification Description: This application is an example of using JPA JOINED inheritance The concept of lightweight threads that coroutines introduce to Kotlin is not new. Use Kotlin coroutines with Architecture components Kotlin coroutines provide an API that enables you to write asynchronous code. With Kotlin coroutines, you can define a CoroutineScope , which helps you to manage when your coroutines should run.

A Bottom-Up View of Kotlin Coroutines, In Kotlin coroutines the compiler implements only the suspend keyword, with Implementations exist in many other languages, including Scala  Now collection happens in one coroutine ("coroutine#1") and emission happens in another coroutine ("coroutine#2") that is running in another thread concurrently with the collecting coroutine. The flowOn operator creates another coroutine for an upstream flow when it has to change the CoroutineDispatcher in its context.

Comments
  • But how do I add the result to the list again then?
  • awaitAll return list of results. kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/…
  • I did this val s : MutableList<Deferred<Iterable<Step>>> = mutableListOf() and added all deffreds but when I did d : Iterable<Step> = awaitAll(s) I am getting an error.
  • What kind of error? Don't you think it is worth of mentioning that ?