@OneToOne与附加约束的关系

时间:2015-01-22 11:28:26

标签: java hibernate jpa orm one-to-one

假设我们有两个实体,第一个:

@Entity
@Table(name = "entitya")
public class EntityA {

  @Id
  @Column(name = "id")
  private Long id;

  @Column(name = "name")
  private Long name;

  @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
  private Set<EntityB> childEntities;

}

和第二个:

@Entity
@Table(name = "entityb")
public class EntityB {

  @Id
  @Column(name = "id")
  private Long id;

  @Column(name = "name")
  private String name;

  @Column(name = "master")
  private Boolean master;

  @ManyToOne
  @JoinColumn(name = "parent")
  private EntityA parent;

}

到目前为止,这么好。但是,基础数据库表和约束强制执行任何entityA,只有一个EntityB布尔字段master设置为true。我可以通过向entityA添加以下方法来提取它:

public entityB getMasterChild() {

  for(entityB ent : childEntities) {
    if(ent.isMaster()) {
      return ent;
    }
  }

}

问题是,我可以在@OneToOne中创建可以表达该规则的EntityA关系,以便entityA可以拥有类型为entityB的其他masterChild成员吗?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你想根据某个实体的属性值创建/定义两个实体之间的关系。认为实体之间的关系是根据实体数量(有多少实体可以拥有另一个实体)而不是某个实体的属性值来定义的。

然而
如果您真的想对@OneToOne使用masterChild映射,我建议为它创建一个单独的表/实体。完成此操作后,您可以将此新MasterChild实体添加到EntityA并使用@OneToOne对其进行注释。

这是新的MasterChild实体

@Entity
public class MasterChild extends EntityB{

  @Id
  @Column(name = "id")
  private Long id;    
}

请注意,我已删除了&#39; master&#39;来自EntityB,因为它不再需要

@Entity
@Table(name = "entityb")
public class EntityB {

  @Id
  @Column(name = "id")
  private Long id;

  @Column(name = "name")
  private String name;

  @ManyToOne
  @JoinColumn(name = "parent")
  private EntityA parent;

}

这里修改了EntityA

@Entity
@Table(name = "entitya")
public class EntityA {

  @Id
  @Column(name = "id")
  private Long id;

  @Column(name = "name")
  private Long name;

  @OneToOne
  private MasterChild master;

  @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
  private Set<EntityB> childEntities;

}