如何使用OneToOne双向关系正确管理关联的JPA实体? [英] How to properly manage associated JPA entities with OneToOne BiDirectional relation?
问题描述
假设有两个实体:主实体和从属实体.
Let's say 2 entities are given: master and dependant.
它们通常像dependants.master_id -> masters.id
一样在数据库中定义,即从属实体拥有对主实体的引用.
They are defined in DB usually like dependants.master_id -> masters.id
, i.e. the dependant entity holds the reference to the main entity.
在这种情况下,在JPA one2one双向关联中通常如下所示:
In JPA one2one BiDirectional association in this case usually looks like:
class Master {
@OneToOne(mappedBy="master")
Dependant dependant
}
class Dependant {
@OneToOne
@JoinColumn("master_id")
Master master
}
这种方法导致必须处理关系的双方,例如:
And this approach causes the necessity to deal with both sides of relation like:
Master master = new Master();
Dependant dependant = new Dependant();
dependant.setMaster(master);
master.setDependant(dependant);
repository.save(master);
而不是像这样更直观,更接近业务逻辑:
instead of more intuitive and closer to business logic one like:
Master master = new Master();
Dependant dependant = new Dependant();
master.setDependant(dependant);
repository.save(master);
有没有通用的解决方法?我的意思是我不想从依赖方面支持协会.
Are there any common workarounds for this? I mean I don't want to mess with supporting the association from the dependant side.
推荐答案
一种解决方法可能是使用@PrePersist
.对于这两个实体,您都可以实现以下方法:
One workaround might be using @PrePersist
. For both entities you could implement methods like:
大师
@PrePersist
private void prePersist() {
if(null == getDependant().getMaster()) {
getDependant().setMaster(this);
}
}
依赖
@PrePersist
private void prePersist() {
if(null == getMaster().getDependant()) {
getMaster().setDependant(this);
}
}
或者也许只是省略空检查.
Or maybe just omitting the null checks.
这篇关于如何使用OneToOne双向关系正确管理关联的JPA实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!