如何维护一个Map在 JPA2 中?

发布于 2024-10-11 03:42:41 字数 1056 浏览 1 评论 0原文

我有三个实体类(ABC)。 A 应包含将 B 实例映射到 C 实例的映射。 C 的所有实例均由某个 A 的映射拥有。我已经尝试过这个(省略 getters 和 setters):

@Entity public class A {
  @Id @GeneratedValue private Long id;

  // I want to map this in an elegant way:
  @OneToMany(mappedBy="a") @MapKey(name="b") private Map<B, C> map;
}

@Entity public class B {
  @Id @GeneratedValue private Long id;
}

@Entity public class C {
  @Id @GeneratedValue private Long id;

  // I don't really want the following in Java, unidirectional access from A to C would suffice:
  @ManyToOne private A a;
  @ManyToOne private B b;
  // Can I get rid of a and b?
}

这提供了一个很好的模式(正是我想要的模式!),但是在 Java 中,由于现在有两种方法来指定关系:

a.map.put(b, c);

c.a = a;
c.b = b;

如果我只改变关联的一半会发生什么 这看起来有问题。解决这个问题的最佳方法是什么?对于所需的单向访问,是否有一些更优雅的解决方案?

我考虑过将 C @Embeddable 并为 A.map 使用 @ElementCollection,但实际上 C 是不同实体的抽象基类,意味着它不能被@Embeddable。

I have three entity classes (A, B, C). A should contain a map which maps instances of B to instances of C. All instances of C are owned by a map of some A. I've tried this (getters and setters omitted):

@Entity public class A {
  @Id @GeneratedValue private Long id;

  // I want to map this in an elegant way:
  @OneToMany(mappedBy="a") @MapKey(name="b") private Map<B, C> map;
}

@Entity public class B {
  @Id @GeneratedValue private Long id;
}

@Entity public class C {
  @Id @GeneratedValue private Long id;

  // I don't really want the following in Java, unidirectional access from A to C would suffice:
  @ManyToOne private A a;
  @ManyToOne private B b;
  // Can I get rid of a and b?
}

That gives a nice schema (exactly the one that I want!), but in Java there's ugly duplication given that there are now two ways to specify the relation:

a.map.put(b, c);

and

c.a = a;
c.b = b;

What happens if I just change one half of the association? That looks problematic. What is the best way around that? Isn't there some more elegant solution for the required unidirectional access?

I considered making C @Embeddable and use an @ElementCollection for A.map, but in reality C is an abstract base class for different entities which means that it can't be made @Embeddable.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

春花秋月 2024-10-18 03:42:41

不确定您想要哪种模式,但您可以使用 < code>@MapKeyJoinColumn 以使此关系单向,请参阅 javadoc 中的示例 1。

Not sure what kind of schema do you want, but you can use @MapKeyJoinColumn to make this relationship unidirectional, see example 1 in javadoc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文