constructor只接受被引用实体的id,但是getter返回实体本身-可能吗?

mefy6pfw  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(300)

让我们假设,我有一个简单的 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
)

我的问题是:构造一个 Student ,我始终需要的示例(已持久化) Teacher 也。因为我只有 ID 对于手边的老师,我首先要获得满分 Teacher 实体,然后将其传递给 Student :

val responsibleTeacher = getTeacherFromDB(teacherId)
val student = Student(responsibleTeacher)

我只想通过 Teacher 构造函数中的id,但仍然能够查询完整的 Teacher 实体来源 Student 调用getter/属性时。

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
)

我花了将近一天的时间来处理这个问题,但找不到任何有效的解决办法。有吗?

bttbmeg0

bttbmeg01#

为此,您可以使用一个代理,通过调用 entityManager.getReference(Teacher.class, teacherId)

jv4diomz

jv4diomz2#

使用 @JoinColumn 注解

@Column(name = "responsible_teacher_id")
   private var responsibleTeacherId: Long,

   @JoinColumn(name = "responsible_teacher_id")
   @OneToOne(fetch = LAZY, insertable = false, updatable = false)
   var responsibleTeacher: Teacher

相关问题