两个具有“拥有关系”的Java实体可以使用同一个表吗?

huangapple go评论80阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年8月27日 00:19:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63601715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定