在单独的表中映射@Embeddable [英] Mapping an @Embeddable in a separate table

查看:85
本文介绍了在单独的表中映射@Embeddable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个表,如:

CREATE TABLE foo (
  id INT PRIMARY KEY,
  x TEXT
);

CREATE TABLE bar (
  foo_id INT REFERENCES foo (id) ON DELETE CASCADE,
  y TEXT,
  z TEXT
);

...可以这样映射:

...can be mapped like so:

@Table(name = "foo")
@SecondaryTable(name = "bar", pkJoinColumns = @PrimaryKeyJoinColumn(name = "foo_id", referencedColumnName = "id"))
class Foo {

  @Id
  int id;

  @Embedded
  @AttributeOverrides({
    @AttributeOverride(name = "y", column = @Column(table = "bar")),
    @AttributeOverride(name = "z", column = @Column(table = "bar"))
  })
  Bar bar;
}

@Embeddable
class Bar {
  String y;
  String z;
}

使用标准的JPA批注或特定于Hibernate的批注(并且在可嵌入对象中未引入父级引用)进行映射时,是否有一种不太尴尬的方式?

Is there a less awkward way to do this mapping, using either just standard JPA annotations, or else Hibernate-specific annotations (and without introducing a parent reference in the embeddable object)?

将此与使用@ElementCollection@CollectionTable引用@Embeddable对象的集合的难易程度进行比较.

Compare this to how easily a collection of @Embeddable objects can be referenced using an @ElementCollection and @CollectionTable.

推荐答案

很抱歉,我的答案很晚,但是这个问题使我很感兴趣,所以我认为我会对此加以解决.

Sorry for the late answer, but the question interested me so I figured I'd take a crack at it.

一种更优雅的解决方案是使bar的内容成为实体而不是Embeddable,并使用OneToOne关系而不是Embedded.您还需要记住使用@PrimaryKeyJoinColumn而不是@JoinColumn:

A more elegant solution is to make the contents of bar an Entity instead of an Embeddable, and to use a OneToOne relationship instead of an Embedded. You also need to remember to use @PrimaryKeyJoinColumn instead of @JoinColumn:

@Entity
@Table(name = "bar")
class Bar {
  @Id
  int fooId;

  String y;
  String z;
}

...

@Entity
@Table(name = "foo")
class Foo {
  @Id
  int id;

  @OneToOne
  @PrimaryKeyJoinColumn
  Bar bar;
}

最大的优点是Foo不再需要了解Bar的内容.根据数据库的命名策略,您可能还需要在Bar中用@Column(name = "foo_id")之类的名称指定fooId的列名.

The biggest advantage is that Foo no longer needs to know about the contents of Bar. Depending on your DB's naming strategy, you may also need to specify the column name of fooId in Bar with something like @Column(name = "foo_id").

这篇关于在单独的表中映射@Embeddable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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