spring-projects / spring-data-jpa

Simplifies the development of creating a JPA-based data access layer.
https://spring.io/projects/spring-data-jpa/
Apache License 2.0
2.93k stars 1.39k forks source link

JpaRepository.getReferenceById not working in Kotlin project #3525

Closed bayy1216 closed 6 days ago

bayy1216 commented 6 days ago

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