【发布时间】:2011-10-19 13:35:54
【问题描述】:
我的数据库中有两个表。带有 ID 和其他一些列的 Table1。 Table2 是一个关系表,其中我将 table1 中的 PK 作为 table2 中的 id,但我在 Table2 中没有使用 ID,它保存了一些其他随机数据的值。
在 JPA 中,您必须使用 @Id 注释。我的问题是我想使用 table1 的实体作为 table2 实体的@Id。这可能吗?如果可以,那怎么办?
到目前为止的代码: 表一
@Entity
@Table(name="Log", schema="logs")
@PersistenceUnit(name="domas")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name="type", discriminatorType = DiscriminatorType.STRING)
public abstract class Log implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="id", nullable=false)
public String id;
@Column(name="type", nullable=false)
@Enumerated(EnumType.STRING)
public LOG_TYPE type;
// and alot more not related code
表 2
@Entity
@Table(name="Log_Entity", schema="relations")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "relationType", discriminatorType = DiscriminatorType.STRING)
public abstract class LogRelation implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@OneToOne(mappedBy="id")
public Log log;
// and alot more not related code
【问题讨论】:
-
您是否要创建另一个表的表 ID?或者您是否尝试从一个表中选择一些字段并尝试为另一个表形成一个复合主键?如果是,那么您应该查看注释
@Embeddable和@EmbeddedId。 -
我只是想将 PK 从 Table1 获取到 Table2 中,这样我就不必在 table2 实体上声明 Id 注释,因为我在 Table2 中没有真正的 ID 列,只有一个 refId从表 1。但是 JPA 强迫我使用 Id-annotation 所以我试图解决它