Using an entity (and primary key) as another object identifier

So, I'm not sure how to ask this question, since it seems pretty easy to find the answer to this question.

I have 3 tables; ContentHeader, ContentType1 and ContentType2. ContentHeader has a primary key with auto-increment. ContentType1 and ContentType2 support foreign keys for the primary key ContentHeader. These foreign keys are also primary keys for the corresponding tables.

CREATE TABLE contentHeader (contentID INT AUTO_INCREMENT PRIMARY KEY, ...) ENGINE=InnoDB;

CREATE TABLE contentType1 (contentID INT PRIMARY KEY, FOREIGN KEY (contentID) REFERENCES contentHeader (contentID), ...) ENGINE=InnoDB;

CREATE TABLE contentType2 (contentID INT PRIMARY KEY, FOREIGN KEY (contentID) REFERENCES contentHeader (contentID), ...) ENGINE=InnoDB;

I created four classes:

@Entity
public class ContentHeader {

  @Id
  @GeneratedValue
  protected int contentID;

  ...
}

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Content {

  @Id
  @OneToOne
  protected ContentHeader contentHeader;

  ...
}

@Entity
public class ContentType1 extends Content {
  ...
}

@Entity
public class ContentType2 extends Content {
  ...
}

This causes a null pointer when trying to generate a circuit. I am pretty sure that I just missed something simple. I noticed PrimaryKeyJoinColumn, but I'm not sure if I need it or not.

+1
1
You can create a composite id class that only have the ContentHeader:

@Embeddable
public class ContentKey implements java.io.Serializable {

    @ManyToOne(cascade = {}, fetch = FetchType.LAZY)
    @JoinColumn(name = "ID", updatable = true)
    private ContentHeader header;
    // ...
}

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Content {

    @Id
    public ContentKey  getContentKeyId()
    // ...
}

.

+2

All Articles