spy*_*yro 6 spring hibernate jpa kotlin
让我们假设,我有一个Student和Teacher实体的简单关系
我正在使用带有 kotlin-jpa 插件的 Spring Boot,所以数据类应该可以正常工作:
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
)
Run Code Online (Sandbox Code Playgroud)
我的问题:要构造 的实例Student,我始终还需要(已持久化)的实例Teacher。由于我ID手头只有老师的 ,我首先需要Teacher从数据库中获取完整的实体,然后将其传递给 的构造函数Student:
val responsibleTeacher = getTeacherFromDB(teacherId)
val student = Student(responsibleTeacher)
Run Code Online (Sandbox Code Playgroud)
我想要的是Teacher在构造函数中只传递ID,但仍然能够在调用 getter/property 时查询完整Teacher实体Student。
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
)
Run Code Online (Sandbox Code Playgroud)
我搞砸了将近一天,但找不到任何可行的解决方案。有没有?
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |