【发布时间】:2021-11-27 17:23:12
【问题描述】:
我有三个实体,其中两个每个都包含第三个的集合。当我通过使用第三个实例创建两个“拥有”实体来设置它们时,只有一个可以正常工作。另一个在添加时抛出此异常,即使集合的设置方式完全相同:
“拥有”实体:
@Entity
class Source(
@OneToMany(mappedBy = "source", cascade = [CascadeType.ALL])
var targets: MutableSet<Target> = mutableSetOf(),
@Id @GeneratedValue
var id: Long? = null,
) {
fun addTarget(target: Target) {
targets.add(target)
target.source = this
}
}
@Entity
class Job(
@OneToMany(mappedBy = "job", cascade = [CascadeType.ALL])
var targets: MutableSet<Target> = mutableSetOf(),
@Id @GeneratedValue
var id: Long? = null,
) {
fun addTarget(target: Target) {
targets.add(target) // exception actually thrown here
target.job = this
}
}
共同“拥有”的实体:
@Entity
class Target(
@ManyToOne var source: Source? = null,
@ManyToOne var job: Job? = null,
@Id @GeneratedValue var id: Long? = null
)
设置如下:
@PostConstruct
@Transactional
fun init() {
val initialJob = Job()
initialJob.targets = mutableSetOf() // no idea why this is necessary, but without it I get the exception
jobRepository.save(initialJob)
val source = Source()
sourceRepository.save(source)
val target = Target()
source.addTarget(target) // this works fine
initialJob.addTarget(target) // but this doesn't unless I initialize the set above
targetRepository.save(target)
sourceRepository.save(source)
jobRepository.save(initialJob)
}
我很困惑为什么我需要手动初始化 Job 实体上的集合,而不是 Source 实体上的集合,因为在我看来这些关系是完全相同的。另外,Job 实体已经在其构造函数中初始化集合。
【问题讨论】:
标签: java spring-boot hibernate kotlin jpa