temesgen
temesgen

Reputation: 47

can two Java Entities that have "Has a" relationship use the same table

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;
  }

Upvotes: 0

Views: 102

Answers (1)

Daniel Jacob
Daniel Jacob

Reputation: 1536

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.

Upvotes: 2

Related Questions