英文:
can two Java Entities that have "Has a" relationship use the same table
问题
我有两个表 A 和 B:
@Entity
public class A {
}
@Entity
public class B {
private final A a;
private String someBSpecificField;
}
实体类 A 已经很好地编码并映射到了现有的表。我的任务是创建 B,出于某种原因,我更倾向于在 A 和 B 之间使用组合而不是继承。与此同时,我希望在读取时将 A 和 B 放在同一个表中,以避免连接操作。我可以这样做吗:
@Entity
@Table(name = "a")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "a_type_enum", discriminatorType =
DiscriminatorType.INTEGER)
@DiscriminatorValue("100")
public class A {
}
@Entity
@Table(name = "a")
@DiscriminatorValue("500")
public class B {
private final A a;
private String someBSpecificField;
}
英文:
I have two tables A and B:
@Entity
public class A {
}
@Entity
public class B {
private final A a;
private String someBSpecificField;
}
Entity A is already Coded nicely and mapped to an existing table. My job is to create B and for some reason I prefer composition over inheritance between A and B. At the same time I want to have single table for A and B to avoid joins when reading. Can I do like this:
@Entity
@Table(name = "a")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "a_type_enum", discriminatorType =
DiscriminatorType.INTEGER)
@DiscriminatorValue("100")
public class A {
}
@Entity
@Table(name = "a")
@DiscriminatorValue("500")
public class B {
private final A a;
private String someBSpecificField;
}
答案1
得分: 2
如果类型是复杂对象,则需要使用 @Embeddable
对该类型进行注解,并在您的 @Entity
类中使用它。
如果您想要覆盖 @Embeddable
类的属性名称,使它们具有不同的列名称,可以使用 @AttributeOverrides
注解来实现。
英文:
If the type is a complex object then you need to annotate that type with @Embeddable
and use it in your @Entity
class.
if you want to override the attribute names for your @Embeddable
class so they have different column names, you can do so with the @AttributeOverrides
annotation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论