Let's assume, I've a simple relationship of Student
and Teacher
Entities
I'm using Spring Boot with kotlin-jpa plugin, so data classes should work fine:
data class Student(
@Id
@GeneratedValue(strategy = IDENTITY)
val id: Long = null,
@OneToOne(fetch = FetchType.LAZY)
var responsibleTeacher: Teacher,
// ... other props
)
data class Teacher(
@Id
@GeneratedValue(strategy = IDENTITY)
val id: Long = null,
val name: String,
// ... other props
)
My problem: To construct an instance of Student
, I always need an instance of the (already persisted) Teacher
as well. As I only have the ID
of the teacher at hand, I first need to obtain the full Teacher
entity from the database and then pass it to the constructor of Student
:
val responsibleTeacher = getTeacherFromDB(teacherId)
val student = Student(responsibleTeacher)
What I would like to to, is to pass only the Teacher
ID in the constructor, but still being able to query the full Teacher
entity from Student
when calling the getter/property.
data class Student(
@Id
@GeneratedValue(strategy = IDENTITY)
val id: Long = null,
@Column(name = "responsible_teacher_id")
private var responsibleTeacherId: Long,
// ... other props
// pseudo-code, doesn't work!
// Should query the [Teacher] Entity by [responsibleTeacherId], specified in constructor
@OneToOne(fetch = LAZY)
var responsibleTeacher:Teacher
)
I was messing around with this for almost a day but couldn't find any working solution. Is there any?
For this purpose you can use a proxy that you can retrieve by calling entityManager.getReference(Teacher.class, teacherId)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With