gpt4 book ai didi

java - 使用 JPA (+Hibernate) 继承抽象类

转载 作者:IT老高 更新时间:2023-10-28 20:44:49 29 4
gpt4 key购买 nike

您将如何在以下示例代码中配置注释?我只想坚持使用 JPA 注释并避免 Hibernate 特定的依赖项。 下面的代码正确吗?

@Entity
public class RefExample extends RefData {

}

(这些类将有多个版本,RefSomeOtherExample 等,每个类一个 db 表。有些可能会添加额外的字段(列),但大多数会简单地使用从“RefData”基类继承的基本字段.)

基类:

@Entity
public abstract class RefData {

private long id;
private String code;
private String desc;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = false)
public long getId() {

return id;
}

public void setId(long id) {

this.id = id;
}

@Column(unique = true, nullable = false, length=8)
public String getCode() {

return code;
}

public void setCode(String code) {

this.code = code;
}

@Column(unique = true, nullable = false, length=80)
public String getDesc() {

return desc;
}

public void setDesc(String desc) {

this.desc = desc;
}
}

最终,我想使用 Hibernate 的 SchemaExport 类从中生成模式创建脚本。在上述情况下,这两个类只应导致创建一个名为“RefExample”的表,其中包含来自“RefData”的三列。这行得通吗?

最佳答案

来自 JPA 1.0 规范:

Both abstract and concrete classes can be entities. Both abstract and concrete classes can be annotated with the Entity annotation, mapped as entities, and queried for as entities.

Entities can extend non-entity classes and non-entity classes can extend entity classes.

如果你想要一个表,你应该使用 Single Table继承。

只需定义一个鉴别器列如下:

@Entity
@DiscriminatorColumn(name="REF_TYPE")
public abstract class RefData {

但如果你不想依赖 JPA 继承策略,你可以使用 MappedSuperclass 代替:

@MappedSuperclass
public abstract class RefData {

JPA 规范

An entity may inherit from a superclass that provides persistent entity state and mapping information, but which is not itself an entity. Typically, the purpose of such a mapped superclass is to define state and mapping information that is common to multiple entity classes.

请记住您不能同时使用@Entity 和@MappedSuperclass。

关于java - 使用 JPA (+Hibernate) 继承抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3827494/

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