开发者

How else to ensure the order of a @ManyToMany List?

Consider:

@Entity
public class M {

    @ManyToMany
    private List<E> es = new ArrayList<E>();
    private E newE;

    public M(E newE) {
        this.newE = newE;
        es.add(newE);
    }

Cannot I assert(m.newE == m.getEs(0))?

I could 开发者_开发知识库only if after rebooting the app/PU is:

  public List<E> getEs() {
    final int indexOf = es.indexOf(newE);
    if (indexOf != 0) {
        es.remove(indexOf);
        es.add(0, newE);
    }
    return Collections.unmodifiableList(es);
}

However this burdensome code is even inefficient as it forces loading the E entitities from the PU before they may actually be needed. Any alternative that works?


Cannot I assert(m.newE == m.getEs(0))?

No, if there are any objects in the @ManyToMany, newE will be added at the end of the list. Also, I believe the list will be lazy-loaded before the insert, so your concern about things being inefficient doesn't really apply.

If you're only concerned about the ordering of elements when loaded from the persistence unit, @OrderBy will do the trick.

@ManyToMany
@Orderby("someproperty ASC")
private List<E> es = new ArrayList<E>();

If you also want to maintain order at runtime while adding elements, you'll have to implement compareTo() or a separate Comparator, then use Collections.sort(), or use a naturally sorted collection like SortedSet.


JPA also provides an @OrderColumn if you want the order maintained.

See this link

Otherwise changes to the order of the elements of the list are not considered a persistent change.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜