Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

spring - 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?

question from:https://stackoverflow.com/questions/65917301/constructor-takes-only-id-of-referenced-entity-but-getter-returns-the-entity-it

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...