开发者

How to maintain a Map<EntityA, EntityB> in JPA2?

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 foll开发者_如何学JAVAowing 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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜