For a @ManyToOne
relation in JPA entity I'm only interested in the actual id reference, not to fetch the whole model associated with the relation.
Take for example these Kotlin JPA entities:
@Entity
class Continent(
@Id
var id: String,
var code: String,
var name: String
) : Comparable<Continent> {
companion object {
private val COMPARATOR = compareBy<Continent> { it.id }
}
override fun compareTo(other: Continent): Int {
return COMPARATOR.compare(this, other)
}
}
@Entity
class Country(
@Id
var id: String,
var alpha2Code: String,
var alpha3Code: String,
var name: String,
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "continent_id")
var continent: Continent
) : Comparable<Country> {
companion object {
private val COMPARATOR = compareBy<Country> { it.id }
}
override fun compareTo(other: Country): Int {
return COMPARATOR.compare(this, other)
}
}
Now when I access country.continent.id
from my Kotlin code the full Continent
is actually queried from the database.
This is overkill as I'm only interested in the Continent.id
.
I've tried adding @Access(AccessType.PROPERTY)
like:
@Entity
class Continent(
@Id
@Access(AccessType.PROPERTY)
var id: String,
but it doesn't make a difference. The whole Continent
is still queried from the database.
I tried the @Access(AccessType.PROPERTY)
as it was mentioned in other posts (like Hibernate one-to-one: getId() without fetching entire object), but I already noticed mixed feedback about this.
I'm using Hibernate 5.3.7.Final
with Kotlin 1.3.0
.
I wonder if 1) the @Access(AccessType.PROPERTY)
approach is correct and 2) should this also be working with Kotlin? Maybe the way Kotlin generated the Java code is causing an issue?
UPDATE
I created a simple test project proving the continent is being queried. https://github.com/marceloverdijk/hibernate-proxy-id
The project contains a simple test retrieving country.continent.id
and SQL logging is enabled. From logging can be seen the continent is queried.
UPDATE 2
I've created https://youtrack.jetbrains.net/issue/KT-28525 for this.