【问题标题】:How else to ensure the order of a @ManyToMany List?如何确保@ManyToMany 列表的顺序?
【发布时间】:2011-09-03 05:42:28
【问题描述】:

考虑:

@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);
    }

我不能assert(m.newE == m.getEs(0))吗?

只有在重新启动应用程序/PU 后我才能:

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

但是,这种繁重的代码甚至效率低下,因为它强制在实际需要之前从 PU 中加载 E 实体。有什么可行的替代方案吗?

【问题讨论】:

    标签: jpa jpa-2.0 eclipselink


    【解决方案1】:

    我不能assert(m.newE == m.getEs(0))吗?

    ,如果@ManyToMany中有任何对象,newE将被添加到列表末尾。另外,我相信列表会在插入之前延迟加载,因此您对效率低下的担忧并不真正适用。

    如果您只关心从持久性单元加载时元素的顺序,@OrderBy 可以解决问题。

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

    如果您还想在添加元素时在运行时保持顺序,则必须实现compareTo() 或单独的Comparator,然后使用Collections.sort(),或使用自然排序的集合,如SortedSet

    【讨论】:

      【解决方案2】:

      JPA 还提供@OrderColumn,如果您希望保持订单。

      See this link

      否则对列表元素顺序的更改不会被视为持久更改。

      【讨论】:

        猜你喜欢
        • 2022-12-24
        • 1970-01-01
        • 1970-01-01
        • 2012-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-27
        • 2017-07-03
        相关资源
        最近更新 更多