使用一个实体(及其主键)作为另一个实体的 Id [英] Using an Entity (and their Primary Key) as another Entity's Id

查看:27
本文介绍了使用一个实体(及其主键)作为另一个实体的 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.

我有 3 张桌子;ContentHeader、ContentType1 和 ContentType2.ContentHeader 有一个主要的、自动递增的键.ContentType1 和 ContentType2 都维护 ContentHeader 主键的外键.这些外键也是它们各自表的主键.

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;

我创建了四个类:

@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 {
  ...
}

这在尝试生成架构时会抛出一个空指针.我很确定我只是缺少一些简单的东西.我注意到了 PrimaryKeyJoinColumn,但我不确定它是否是我需要的.

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.

推荐答案

您可以创建一个只有 ContentHeader 的复合 id 类:

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()
    // ...
}

这应该可以解决问题.

这篇关于使用一个实体(及其主键)作为另一个实体的 Id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆