Skip to content

JpaRepository.getReferenceById not working in Kotlin project #3525

@bayy1216

Description

@bayy1216

While studying data-jpa, I learned that using getReferenceById reduces select queries when creating entities through ManyToOne relationships.
However, when I tested this in a Kotlin project, calling getReferenceById immediately executed the select query, and the proxy object was not returned.

When the same test was performed in Java, the proxy object was successfully returned.

package com.reditus.reftestkotlin

import jakarta.persistence.EntityManager
import jakarta.persistence.EntityNotFoundException
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.transaction.annotation.Transactional

@SpringBootTest
class RefTestKotlinApplicationTests(

    @Autowired private val userRepository: UserRepository,
    @Autowired private val entityManager: EntityManager,
) {

    @Test
    @Transactional
    fun testRef() {

        val user = User.fixture(
            nickname = "testUser"
        )
        userRepository.save(user)
        println(user.id)
        entityManager.clear()
        val id = user.id!!

        println("[Trying]=======get proxy object======")
        val ref = userRepository.getReferenceById(id)
        println(ref.javaClass.name)
        println("[End Trying]===========")


        println("[Trying]=======get user info from proxy object======")

        println(user.nickname)

        println("[End Trying]===========")

//        val notExistRef = userRepository.getReferenceById(100L)
//        assertThrows<EntityNotFoundException> {
//            println(notExistRef.nickname)
//        }


    }

}

image

Here's my sample code

doesn't work in kotlin
https://github.com/bayy1216/RefSample/blob/kotlin/src/test/kotlin/com/reditus/reftestkotlin/RefTestKotlinApplicationTests.kt
It work's in java
https://github.com/bayy1216/RefSample/blob/java/src/test/java/com/reditus/reftestjava/RefTestJavaApplicationTests.java

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions