Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

hibernate - Using an Entity (and their Primary Key) as another Entity's Id

So, I'm not sure how to ask this question, as it seems like it should be pretty easy to find the answer to this one.

I have 3 tables; ContentHeader, ContentType1 and ContentType2. ContentHeader has a primary, auto-increment key. ContentType1 and ContentType2 both maintain foreign keys to ContentHeader's primary key. These foreign keys are also the primary keys for their respective 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 have 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 throws a null pointer when trying to generate the schema. I'm pretty sure I'm just missing something simple. I noticed the PrimaryKeyJoinColumn, but I'm not sure if it's what I need or not.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can create a composite id class that only has 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()
    // ...
}

That should do the trick.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...