<zk>
<window title="ZK Listbox - Load model from DB" border="normal"
apply="org.zkoss.bind.BindComposer"
viewModel="@id('vm') @init('fiddle.DBViewModel')">
<listbox mold="paging" model="@load(vm.model)">
<listhead>
<listheader label="name"/>
<listheader label="name again"/>
</listhead>
<template name="model">
<listitem>
<listcell>
<label value="@load(each)"/>
</listcell>
</listitem>
</template>
</listbox>
<button label="Clear Cache" onClick="@command('clearCache')"/>
</window>
</zk>
自定义一个DBListModel:
package fiddle;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.zkoss.zul.AbstractListModel;
public abstract class DBListModel<T> extends AbstractListModel<T> {
private static final long serialVersionUID = 1L;
private int chunkSize;
private Integer totalSize = null;
private Map<Integer, List<T>> chunkCache = new HashMap<Integer, List<T>>();
public DBListModel(int chunkSize) {
super();
this.chunkSize = chunkSize;
}
@Override
public T getElementAt(int index) {
int chunkIndex = index / chunkSize;
List<T> chunkElements = chunkCache.get(chunkIndex);
if(chunkElements == null) {
chunkElements = loadChunkFromDB(chunkIndex * chunkSize, chunkSize);
chunkCache.put(chunkIndex, chunkElements);
}
return chunkElements.get(index % chunkSize);
}
@Override
public int getSize() {
if(totalSize == null) {
totalSize = loadTotalSize();
}
return totalSize;
}
public void clearCaches() {
totalSize = null;
chunkCache.clear();
}
protected abstract int loadTotalSize();
protected abstract List<T> loadChunkFromDB(int startIndex, int size);
}
viewmodel实现:
package fiddle;
import java.util.ArrayList;
import java.util.List;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.util.Clients;
public class DBViewModel {
fiddle.DBListModel<String> model;
@Init
public void init() {
model = new fiddle.DBListModel<String>(100) {
@Override
protected int loadTotalSize() {
//in the real app you would call a service and load the count from the DB
//SQL could be: SELECT COUNT(name) FROM person_table;
return 1350;
}
@Override
protected List<String> loadChunkFromDB(int startIndex, int size) {
//in the real app you would call a service and load the chunk of data from the DB
//SQL could be: SELECT name FROM person_table LIMIT $size OFFSET $startIndex;
Clients.showNotification(String.format("loaded %d elements starting from position %d", size, startIndex));
List<String> results = new ArrayList<String>(size);
for(int i = startIndex; i < startIndex + size; i++) {
results.add("Name #" + i);
}
return results;
}
};
}
@Command("clearCache")
@NotifyChange("model")
public void doClearCache() {
model.clearCaches();
}
public DBListModel<String> getModel() {
return model;
}
}