2011-09-03 45 views
0

考慮:如何確保@ManyToMany列表的順序?

@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 entitities實際上可能需要之前。任何可行的替代方案?

回答

0

Can not I 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

0

JPA如果您要維護訂單,還會提供@OrderColumn

See this link

否則更改名單的元素的順序不被認爲是一個持久的變化。

相關問題