我不知道如何在标题中描述我的问题,但我希望它能做到。
这就是我的情况。

我使用休眠将我的实体映射到数据库表。

我有一个这样的实体:

@Entity
@Table(name = "EX.EXAMPLE")
public abstract class Entity
{
  private CustomEntity customEntity;
  public static final String CUSTOM_ENTITY = "customEntity";

  @OneToOne(cascade = CascadeType.ALL, mappedBy = CustomEntity.ENTITY, fetch = FetchType.LAZY)
  @Fetch(FetchMode.SELECT)
  public CustomEntity getCustomEntity()
  {
    return this.customEntity;
  }
}


还有我的CustomEntity

    @Entity
    @Table(name = "EX.EXAMPLE2")
    public class CustomEntity
    {
      private Entity entity;
      public static final String ENTITY = "entity";

      @OneToOne
      @JoinColumn(name = "ID_ENTITY", nullable = true)
      public Entity getEntity()
      {
        return this.ntity;
      }
    }


所以这是我的问题:是否可以向Entity添加另一个CustomEntity关系?以及我如何映射它?
示例我的意思是:

    @Entity
    @Table(name = "EX.EXAMPLE")
    public abstract class Entity
    {
      private CustomEntity customEntity;
      public static final String CUSTOM_ENTITY = "customEntity";

      private CustomEntity customEntity2;
      public static final String CUSTOM_ENTITY2 = "customEntity2";


      @OneToOne(cascade = CascadeType.ALL, mappedBy = CustomEntity.ENTITY, fetch = FetchType.LAZY)
      @Fetch(FetchMode.SELECT)
      public CustomEntity getCustomEntity()
      {
        return this.customEntity;
      }

      @OneToOne(cascade = CascadeType.ALL, mappedBy = CustomEntity.ENTITY, fetch = FetchType.LAZY)
      @Fetch(FetchMode.SELECT)
      public CustomEntity getCustomEntity2()
      {
        return this.customEntity2;
      }
    }


我仅通过将customEntity更改为Entity中的列表来进行管理。

问候

最佳答案

是的,那是完全正常的情况。您只需要两个字段具有不同的mappingBy`,每个关系一个

  @OneToOne(cascade = CascadeType.ALL, mappedBy = CustomEntity.ENTITY1, fetch = FetchType.LAZY)
  @Fetch(FetchMode.SELECT)
  public CustomEntity getCustomEntity()
  {
    return this.customEntity;
  }

  @OneToOne(cascade = CascadeType.ALL, mappedBy = CustomEntity.ENTITY2, fetch = FetchType.LAZY)
  @Fetch(FetchMode.SELECT)
  @JoinColumn(name = "entity_2_id")
  public CustomEntity getCustomEntity2()
  {
    return this.customEntity2;
  }


CustomEntity中有两个字段,每个字段对应一个

  @OneToOne
  @JoinColumn(name = "ID_ENTITY_1", nullable = true)
  public Entity getEntity1()
  {
    return this.entity1;
  }

  @OneToOne
  @JoinColumn(name = "ID_ENTITY_2", nullable = true)
  public Entity getEntity2()
  {
    return this.entity2;
  }

关于java - 在 hibernate 状态下是否可能有两次相同的“OneToOne”关系?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29920720/

10-11 21:35