gpt4 book ai didi

java - 是否有可能在 hibernate 中有两次相同的 "OneToOne"-Relationship?

转载 作者:行者123 更新时间:2023-11-30 08:53:04 26 4
gpt4 key购买 nike

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

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

我有一个这样的实体:

@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 更改为实体中的列表来管理它。

问候

最佳答案

是的,这是完全正常的情况。您只需要两个具有不同 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 中的两个字段,每个映射一个

  @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"-Relationship?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29920720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com