JPA实体:如何在Parent和多个Child类之间建立关系

时间:2014-12-22 17:47:46

标签: java jpa ejb

我有以下Java类:

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

我需要将Parent,ChildA和ChildB表示为实体bean,每个实体bean在数据库中都有一个相关的表。

当我加载Parent时,我还需要加载ChildA或ChildB,具体取决于关系。

1 个答案:

答案 0 :(得分:3)

如果我说得对,那么class parent是一个与ChildType实体保持一对一关系的实体。 ChildType也是一个抽象实体,有2个实现,ChildA和ChildB。

因此,每个实体的JPA注释配置可能是这样的:

 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
}

最后我们有ChildA和ChildB

正如您所看到的,ChildType子类上不需要id字段,因为 他们从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
}

有关JPA继承

的更多信息

点击此处: