2013-01-04 101 views
1

我正在尋找一些關於處理Wicket中對象集合的最佳方式的幫助或指導,這些對象不會對會話大小產生破壞性影響。顯然,用Wicket的IModel類包裝對象是理想的,但在處理對象集合(例如搜索結果集合)時,最好的方法是什麼。在Wicket中處理模型對象集合的正確方法是什麼?

使用LoadableDetachableModel處理單個對象時,我已經成功了,但在關閉Tomcat時,我似乎間歇性地獲取了java.io.NotSerializableException。起初,我認爲我是安全的,但拋出的異常表明不然。

這是代碼(編輯爲簡潔起見):

public class CandidateSearch extends BasicPage { 

private static final long serialVersionUID = 1L; 
private CandidateService service = new CandidateService(); 

public CandidateSearch() { 
    ListView<Candidate> listView = new ListView<Candidate>("candidates", service.search()){ 

     private static final long serialVersionUID = 1L; 

     @Override 
     protected void populateItem(ListItem<Candidate> item) { 
      Candidate candidate = (Candidate) item.getModelObject(); 

      PageParameters pars = new PageParameters(); 
      pars.add("id", candidate.getId()); 
      Link<String> candidateLink = new BookmarkablePageLink<String>("candidateLink", CandidateDetails.class, pars); 

      candidateLink.add(new Label("candidateId", "ID-" + new Long(candidate.getId()).toString())); 

      item.add(candidateLink); 
      item.add(new Label("name", candidate.getFirstName() + " " + candidate.getLastName())); 
      item.add(new Label("location", candidate.getCity() + ", " + candidate.getState())); 
     } 

    }; 

    add(listView); 

} 

}

注:service.search返回的java.util.List類型爲候選。

回答

2

當你構建這樣的ListView時,你的Candidate對象將不可拆卸...這就是爲什麼你得到java.io.NotSerializableException

我不確定這是否是最佳做法,但我的策略是將對象列表轉換爲列表的LoadableDetachableModel。我有一個實用的方法是這樣的:

public static <T> IModel<? extends List<T>> convertToListViewModel(List<T> objects) { 

    final Class<? extends List> listClass = objects.getClass(); 

    // NOTE: you will need to implement the toLoadableDetachableModels method 
    List<IModel<T>> asModels = toLoadableDetachableModels(objects); 

    return new LoadableDetachableModel<List<T>>() { 
     @Override 
     protected List<T> load() { 
      List<T> results = ClassUtils.newInstance(listClass); 
      for(IModel<T> model : asModels) { 
       results.add(model.getObject()); 
      } 
      return results; 
     } 
    }; 
} 

您可以使用此方法來包裝的service.search()的結果,那麼不僅應該,你應該擺脫錯誤的,但你的對象需要少得多的會話存儲空間。

+0

+1:一種可重複使用的策略,我也有時使用。 –

+0

這是非常好的,非常有幫助。非常感謝你們倆。 – mchandler

2

如果您想要堅持一些與您當前的基本架構接近的東西,那麼stevevis建議將您的列表轉換爲[LoadableDetachableModel][1]的過程是合理的。根據需要和您在做不保持

,將工作以及和出於某些目的也許更好較大的變化將切換到使用DataView,使顯示的數據來源於IDataProvider實現List

這些和其他中繼器的良好示例代碼可以在the wicket examples site找到。

相關問題