All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jfplugin.xsql.statement.ForeachStatement Maven / Gradle / Ivy

The newest version!
package com.jfplugin.xsql.statement;

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

import org.w3c.dom.Node;

import com.jfplugin.xsql.core.Context;
import com.jfplugin.xsql.core.VarParser;

/**
 *  prepend - 可被覆盖的 SQL 语句组成部分,添加在语句的前面(可选) 
 * 	collection - array或者list
 *	open - 整个遍历内容体开始的字符串,用于定义括号(可选) 
 *	close -整个遍历内容体结束的字符串,用于定义括号(可选) 
 *  separator - 分隔符
 *  item 	- List的一条记录
 * @author farmer
 *
 */
public class ForeachStatement extends Statement{

	public ForeachStatement(Node node) {
		super(node);
	}

	@Override
	public void execute(Context ctx, Object localVar) {
		String collection = attr("collection");
		String open = attr("open");
		String close = attr("close");
		String separator = attr("separator");
		String item = attr("item");
		String prepend = attr("prepend");
		Object o = VarParser.parser(collection, ctx.globalVar, localVar);
		ctx.sw.append(prepend).append(open);
		List list = toList(o);
		int size = list.size();
		for (int i = 0; i < size; i++) {
			for (Statement child : children) {
				Map var = new HashMap();
				var.put(item, list.get(i));
				child.execute(ctx, var);
			}
			if(i < size -1){
				ctx.sw.append(separator);
			}
		}
		ctx.sw.append(close);
	}

	
	@SuppressWarnings("unchecked")
	private List toList(Object o){
		if(o instanceof List){
			return (List) o;
		}else if(o instanceof Object[]){
			return Arrays.asList((Object[])o);
		}
		throw new RuntimeException("foreach仅接收List或者Array类型!");
		
	}
	
}