com.jfinal.template.activerecord.ParaInDirective Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of enjoy-sql Show documentation
Show all versions of enjoy-sql Show documentation
the jfinal enjoy plugin for normal java program to use sql management function.
package com.jfinal.template.activerecord;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.TemplateException;
import com.jfinal.template.expr.ast.Const;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.expr.ast.Id;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.ParseException;
import com.jfinal.template.stat.Scope;
/**
* 模块描述:[sql模版,通过指令扩展,参照ParaDirective]
* 作者:林冰清
* 日期:2017/6/12.
*/
public class ParaInDirective extends Directive {
private int index = -1;
private String paraName = null;
private static boolean checkParaAssigned = true;
public ParaInDirective() {
}
public static void setCheckParaAssigned(boolean checkParaAssigned) {
checkParaAssigned = checkParaAssigned;
}
public void setExprList(ExprList exprList) {
if (exprList.length() == 0) {
throw new ParseException("The parameter of #ParaIn directive can not be blank", this.location);
} else {
if (exprList.length() == 1) {
Expr expr = exprList.getExpr(0);
if (expr instanceof Const && ((Const) expr).isInt()) {
this.index = ((Const) expr).getInt().intValue();
if (this.index < 0) {
throw new ParseException("The index of para array must greater than -1", this.location);
}
}
}
if (checkParaAssigned && exprList.getLastExpr() instanceof Id) {
Id id = (Id) exprList.getLastExpr();
this.paraName = id.getId();
}
this.exprList = exprList;
}
}
public void exec(Env env, Scope scope, Writer writer) {
SqlPara sqlPara = (SqlPara) scope.get("_SQL_PARA_");
if (sqlPara == null) {
throw new TemplateException("#paraLike directive invoked by getSqlPara(...) method only", this.location);
} else if (checkParaAssigned && this.paraName != null && !scope.exists(this.paraName)) {
throw new TemplateException("The parameter \"" + this.paraName + "\" must be assigned", this.location);
} else {
// 解析"1,2,3,4"为 ?,?,?,?
String id = String.valueOf(this.exprList.eval(scope));
String[] ids = id.split(",");
for (int i = 0; i < ids.length; i++) {
this.write(writer, "?");
if (i < ids.length - 1) {
this.write(writer, ",");
}
sqlPara.addPara(ids[i]);
}
}
}
}