java—在hibernate中有可能有两次相同的“onetoone”关系吗?

ulmd4ohb  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(357)

我不知道如何在标题中描述我的问题,但我希望可以。这就是我的情况。
我使用hibernate将实体Map到db表。
我有这样一个实体:

@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;
  }
}

还有我的客户实体

@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;
      }
    }

所以我的问题是:是否可以向实体添加另一个customentity关系?我如何绘制Map?举例说明我的意思:

@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中的列表来管理它。
问候语

tsm1rwdh

tsm1rwdh1#

是的,这是完全正常的情况。您只需要两个具有不同mappedby的字段,每个关系对应一个

@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 ,每个Map一个

@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;
  }

相关问题