Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor takes only ID of referenced entity, but getter returns the entity itself - possible?

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?

like image 462
spyro Avatar asked Jan 27 '21 10:01

spyro


1 Answers

For this purpose you can use a proxy that you can retrieve by calling entityManager.getReference(Teacher.class, teacherId)

like image 63
Christian Beikov Avatar answered Nov 09 '22 23:11

Christian Beikov