我有以下对象(简化):

@Entity
@Table(name = "delivery_addresses")
data class DeliveryAddress (
        val street: String
) {

    @ManyToOne(fetch=FetchType.LAZY)
    lateinit var user: User
}

当我通过ID查询对象时
val deliveryAddress = deliveryAddressService.findById(1)

哪个

override fun findById(deliveryAddressId: Long): DeliveryAddress? {
    return deliveryAddressRepository.findById(deliveryAddressId).orElse(null) // JpaRepository
}

我可以看到执行了以下查询:

select deliveryad0_.street as street6_2_0_, deliveryad0_.user_id as user_id8_2_0_, from delivery_addresses deliveryad0_ where deliveryad0_.id=?

select user0_.id as id1_5_0_, user0_.email as email2_5_0_, user0_.password as password3_5_0_, where user0_.id=?

我如何才能使FetchType.LAZY正常工作(也是@Basic(fetch = FetchType.LAZY不适用于我)?

最佳答案

终于,我能够弄清楚了。该问题与kotlin数据类有关(请参阅KT-28525)

人们不应该将数据类与spring-data-jpa一起使用。引用自kotlin spring-guide



为了使延迟获取按预期方式工作,应打开实体。我的解决方案:

build.gradle.kts:

plugins {
  kotlin("plugin.allopen") version "1.3.61"
}

allOpen {
  annotation("javax.persistence.Entity")
  annotation("javax.persistence.Embeddable")
  annotation("javax.persistence.MappedSuperclass")
}

10-02 00:48