ZK Listbox控件从数据库获取数据



	
		
		
			
				
				
			
			
		
                  
                 
		

自定义一个DBListModel:

package fiddle;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zul.AbstractListModel;

public abstract class DBListModel extends AbstractListModel {
	private static final long serialVersionUID = 1L;

	private int chunkSize;

	private Integer totalSize = null;
	private Map> chunkCache = new HashMap>();
	
	public DBListModel(int chunkSize) {
		super();
		this.chunkSize = chunkSize;
	}

	@Override
	public T getElementAt(int index) {
		int chunkIndex = index / chunkSize;
		List 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 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 model;
	
	@Init 
	public void init() {
	
		model = new fiddle.DBListModel(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 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 results = new ArrayList(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 getModel() {
		return model;
	}
}

你可能感兴趣的:(zk,javascript,ui,开发语言)