ps0604
ps0604

Reputation: 1071

JPA entities: How to establish relationship between Parent and multiple Child classes

I have the following Java classes:

public Class Parent {

    int someValue1;

    ChildType child;
}


public Class ChildType {

     int someValue2;
}


public Class ChildA extends ChildType {

     int id;

     String string;
}



public Class ChildB extends ChildType {

    int id;

    Integer integer;
}

I need to represent Parent, ChildA and ChildB as entity beans with each having a related table in the database.

When I load a Parent I also need to load either ChildA or ChildB depending on the relationship.

Upvotes: 0

Views: 2606

Answers (1)

GregoAvg
GregoAvg

Reputation: 116

If i got that right, class parent is an entity that keeps a one-to-one relationship with ChildType entity. Also ChildType is an abstract entity with 2 implementations, ChildA and ChildB.

So the JPA annotations configuration for each one of the entities, could be like that:

 Parent class as Entity
@Entity
@Table(name = "PARENT")
public class Parent { // better name will do the job, because parent is often called
                      // the higher level class of the same hierarchy
  @Id
  @GeneratedValue
  @Column(name = "PARENT_ID")
  private long id;

  @Column(name = "SOME_VALUE") //if you need to persist it
  private int someValue1;

  @OneToOne(optional = false, cascade = CascadeType.ALL)
  @JoinColumn(name = "FK_PARENT_ID")
  private ChildType child;

  // getters and setters
}
 ChildType class as Entity
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class ChildType { // this one is actually called parent class

  @Id
  @GeneratedValue(strategy = GenerationType.TABLE)
  @Column(name = "CHILDTYPE_ID")
  protected Long id;

  @Column(name = "SOME_VALUE_2")
  private int someValue2; // or maybe protected. Depends if you need childs to access it

  @Column(name = "A_STRING")
  private String string; // or maybe protected. Depends if you need childs to access it
  
  // getters and setters
}

Finally we have ChildA and ChildB

As you can see there is no need to have id fields on ChildType child classes, because they inherit this field from ChildType!

 ChildA as Entity
@Entity
@Table(name = "CHILD_A")
public Class ChildA extends ChildType {
  
  @Column(name = "A_STRING")
  private String string;
  
  // getters and setters
}
 ChildB as Entity
@Entity
@Table(name = "CHILD_B")
public Class ChildB extends ChildType {
  
  @Column(name = "AN_Integer")
  private Integer integer;
  
  // getters and setters
}

More information about JPA Inheritance

check here:

Upvotes: 3

Related Questions