gpt4 book ai didi

java - Hibernate + JPA 无法为子类映射不同的 id

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:08:37 24 4
gpt4 key购买 nike

由于在我开始这个项目之前存在的原因,有些表的类型相似但 ID 列不同。

所以,当我尝试这个的时候

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Element implements Serializable {
public String title;
}

@Entity
public class PrimaryElement extends Element {
@Id
long pid;
}

@Entity
public class OtherElement extends Element {
@Id
long oid;
}

然后我得到一个明显的错误

No identifier specified for entity: Element

现在,我不能很好地将 ID 放在 Element 类中,因为它们显然映射到不同的列。

我尝试了各种风格的@Id 和'abstract' 以及@MappedSuperClass 等等..

我完全不知所措。有解决办法吗?

如有任何见解,我们将不胜感激。

谢谢!

最佳答案

您可以用@MappedSuperclass 替换您的 Element 类的@Entity 和@Inheritance 注释(此注释负责技术映射,只有 PrimaryElement 和 OtherElement 将是功能齐全的实体)或使用它的 @Id 注释移动 oid 字段到类 Element 并在其子类中使用 @AttributeOverride 注释来修改列名(在这种情况下,抽象类 Element 也将是一个功能齐全的实体)。

@AttributeOverride(name="oid", column=@Column(name="primary_element_id"))

更新:

@MappedSuperclass
public abstract class Element implements Serializable {
@Id
private long id;
public String title;
}

@Entity
@AttributeOverride(name="id", column=@Column(name="pid"))
public class PrimaryElement extends Element {
}

@Entity
@AttributeOverride(name="id", column=@Column(name="oid"))
public class OtherElement extends Element {
}

关于java - Hibernate + JPA 无法为子类映射不同的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32142718/

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