测试效果: String sqlTemplate = "select * from t_gril where sex = #para(sex) and age in (#paraIn(age)) and name = #para(name)"; Kv cond = Kv.create() .set("sex", 1) .set("name", "dddd") .set("age", "18,19"); SqlPara sp = Db.getSqlPara(sqlTemplate, cond); // String sqlTemplate = "select * from t_gril where sex = #para(0) and age in (#paraIn(1)) and name = #para(2)"; // SqlPara sp = getSqlPara(sqlTemplate, 1,"18,19","ddde"); log.debug(sp.getSql()); log.debug(sp.getPara()[3]+"");
结果输出:
DEBUG - select * from t_gril where sex = ? and age in (?,?) and name = ?
DEBUG - dddd
原码
public class ParaInDirective extends Directive { /** * 描述: */ private int index = -1; /** * 描述: * * @author Robin Zhang * @created 2017年7月7日 下午2:57:23 * @param exprList * @see com.jfinal.template.Directive#setExprList(com.jfinal.template.expr.ast.ExprList) */ public void setExprList(ExprList exprList) { if (exprList.length() == 1) { Expr expr = exprList.getExpr(0); if (expr instanceof Const && ((Const) expr).isInt()) { index = ((Const) expr).getInt(); if (index < 0) { throw new ParseException("The index of para array must greater than -1", location); } } } this.exprList = exprList; } /** * 描述: * * @author Robin Zhang * @created 2017年7月7日 下午2:57:31 * @param env * @param scope * @param writer * @see com.jfinal.template.stat.ast.Stat#exec(com.jfinal.template.Env, * com.jfinal.template.stat.Scope, java.io.Writer) */ public void exec(Env env, Scope scope, Writer writer) { SqlPara sqlPara = (SqlPara) scope.get("_SQL_PARA_"); if (sqlPara == null) { throw new TemplateException("#paraIn invoked by getSqlPara(...) method only", location); } StringBuffer inPlaceholder = new StringBuffer(); String valueStr = ""; if (index == -1) { Expr[] exprArray = exprList.getExprArray(); Object ret = null; for (Expr expr : exprArray) { boolean hasPara = scope.getData().containsKey(expr.toString()); if (hasPara) { ret = expr.eval(scope); if (ret==null) {//in类的参数值不可为空 throw new TemplateException( "The value of parameter '"+expr.toString()+"' must not be null", location); } } else {//没有传参数抛异常 throw new TemplateException( "The parameter '"+expr.toString()+"' must be define", location); } } valueStr = String.valueOf(ret); // sqlPara.addPara(exprList.eval(scope)); } else { Object[] paras = (Object[]) scope.get("_PARA_ARRAY_"); if (paras == null) { throw new TemplateException( "The #paraIn(" + index + ") directive must invoked by getSqlPara(String, Object...) method", location); } if (index >= paras.length) { throw new TemplateException("The index of #paraIn directive is out of bounds: " + index, location); } valueStr = String.valueOf(paras[index]); // sqlPara.addPara(paras[index]); } Object[] retArrray = valueStr.split(","); for (int i = 0; i < retArrray.length; i++) { inPlaceholder.append("?"); if (i != retArrray.length - 1) { inPlaceholder.append(","); } sqlPara.addPara(retArrray[i]); } write(writer, inPlaceholder.toString()); } }
注册paraIn指令:
Engine.addDirective("paraIn", new ParaInDirective());