Hi all,
I've got two classes A and B which have a bidirectional many-to-many
relationship. However, references to B's from A's must be ordered while
references to A's from B's should be unordered. Is there a clean way to
represent this accurately with JPA? I think what I'm looking for is
allowing @OrderBy to reference a special index column within the join
table itself.. if that makes sense.
Here's an outline:
@Entity
public class A {
...
@ManyToMany
@OrderBy(???)
protected List<B> bs;
...
}
@Entity
public class B {
...
@ManyToMany(mappedBy="bs")
protected Collection<A> as;
...
}
I can't use an explicit index field within B because different A's might
reference the same B's, but require different ordering of those B's with
their respective A.bs fields.
Here's an alternative:
@Entity
public class A {
...
@OneToMany(mappedBy="a")
@OrderBy("index")
protected List<BRef> brefs;
...
}
@Entity
public class BRef {
...
@ManyToOne protected A a;
@ManyToOne protected B b;
@Basic protected int index;
...
}
@Entity
public class B {
...
@ManyToMany
protected Collection<A> as;
...
}
But here we see that the declaration of B.as will result in a separate
join table "B_A". Can we instead reuse the table supporting BRef?:
@Entity
public class B {
...
@ManyToMany()
@JoinTable(
name="BRef",
[EMAIL PROTECTED](name="b_id"),
[EMAIL PROTECTED](name="a_id")
)
protected Collection<A> as;
...
}
Okay, but this still means that we have an explicit level of indirection
from A's to B's through BRef's. I'd rather the A to B relation be taken
care of transparently-- I want to be able to reference the BRef.index
field somehow to constrain the ordering of A.bs, perhaps like this:
@Entity
public class A {
...
@ManyToMany()
@JoinTable(
name="BRef",
[EMAIL PROTECTED](name="a_id"),
[EMAIL PROTECTED](name="b_id"),
orderBy="index"
)
protected List<B> bs;
...
}
@Entity
public class BRef {
...
@ManyToOne protected A a;
@ManyToOne protected B b;
@Basic protected int index;
...
}
@Entity
public class B {
...
@ManyToMany(mappedBy="bs")
protected Collection<A> as;
...
}
Thoughts?
Andy