嵌入式和实体之间是否可能存在双向关系或仅存在单向关系?
@Entity
public class Employee {
@Id
private long id;
...
@Embedded
private EmploymentPeriod period;
...
}
@Embeddable
public class EmploymentPeriod {
@Column(name="START_DATE")
private java.sql.Date startDate;
@Column(name="END_DATE")
private java.sql.Date endDate;
@OneToMany
private EntityABCD entityABCD ;
....
}
@Entity
public class EntityABCD {
@Id
private long id;
...
@ManyToOne(mappedby="entityABCD")
private EmploymentPeriod period;
...
}
<小时/>
根据 JPA 规范:2.5 可嵌入类
An entity cannot have a unidirectional relationship to the embeddable class of another entity (or itself).
<小时/>
请按照 JPA 规范的规定澄清上述行。
最佳答案
当每个实体都指向另一个实体时,关系是双向的。
如果只有一个实体指向另一个实体,则关系是单向。
在您的具体情况下,句子:
An entity cannot have a unidirectional relationship to the embeddable class of another entity (or itself)
可以翻译为:
EntityABCD entity cannot have a unidirectional relationship to the embeddable class EmploymentPeriod of another Employee entity.
换句话说:
If Employee entity has an embedded EmploymentPeriod, it is not possible to define an unidirectional relationship from EntityABCD entity to embeddable EmploymentPeriod of entity Employee.
为什么?
由于可嵌入对象没有自己的标识(缺少主键),因此只需将其视为封装它的实体的一部分。 从数据库的角度来看,嵌入对象与其余实体属性存储在一行中。
由于上述原因,如果有人尝试从 EntityABCD
创建单向关系,则 EmploymentPeriod
由于缺乏 EmploymentPeriod
的身份,这是根本不可能的,
因此不可能在嵌入对象中创建外键。
如何解决外键问题?
外键需要在可嵌入类之外物理创建,这取决于关系类型。一个例子(:
@Entity
public class Employee {
@Id
private long id;
@Embedded
private EmploymentPeriod period;
}
@Embeddable
public class EmploymentPeriod {
@ManyToOne //owning relationship
@JoinColumn //FK in EMPLOYEE table (by default: ENTITYABCD_ID)
private EntityABCD entityABCD;
@ManyToMany //owning relationship
@MapKey(name="id") //refers to EntityABCD.id
@JoinTable //FK in the join table (by default: EMPLOYEE_ENTITYABCD)
private Map<Long, EntityABCD> entitiesABCD;
}
@Entity
public class EntityABCD {
@Id
private long id;
@OneToMany(mappedBy = "period.entityABCD") //non-owning relationship
List<Employee> employee;
@ManyToMany(mappedBy="period.entitiesABCD") //non-owning relationship
private List<Employee> employees;
}
当嵌入对象内存在双向关系时,它们被视为存在于所属实体 (Employee
) 中
目标实体 (EntityABCD
) 指向所属实体,而不是嵌入对象 (EmploymentPeriod
)。
值得一提的是,embeddables 只能嵌入:
- 其他嵌入式
- 与实体的关系
- 基本/可嵌入类型的元素集合
关于java - jpa Embeddables 与实体的双向关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21693071/