如何维护一个Map在 JPA2 中?
我有三个实体类(A、B、C)。 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定您想要哪种模式,但您可以使用 < 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.