java - jpa Embeddables 与实体的双向关系

标签 java jpa orm jpa-2.0

嵌入式和实体之间是否可能存在双向关系或仅存在单向关系?

@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/

相关文章:

python - Django 查询互相喜欢的用户

performance - Linq-to-SQL 数据检索速度比较

php - 复制一个包含所有关系的 Doctrine 对象

Java 小程序 "HORIZONTAL"无法解析或不是字段

java - java中文件路径的Windows转义序列问题

java - 结合读取和解析 text.txt

java - 在 EJB-Hibernate 环境中使用 JDBC

java - 为什么 hibernate 不在 OneToMany 的所有者端设置外键

java - 单向关系 : Remove cascade

java - jpa原生查询控制实体(第3部分)