Jfinal 如何实现IN查询呢???

最近公司使用Jfinal做一个小型网站,今天碰到要使用SQL in 函数,卡了好久,刚刚解决,做个备份。

    使用Jfinal 实现in 查询时 传入参数需为 数组类型,(List集合不知道可以不,没有尝试,但理论应该 是可以的)  ,然后使用SQL模板去遍历传入的数组这样就根据你传入的参数多少就会有多少个占位符形成与其匹配。

案例   

   a.(   --and拼接条件
  )


评论区

jfinal009

2018-10-17 16:39

请参考:
FFIELD_STATUS in (
#for(stt : x.value)
#(for.index > 0 ? "," : "") #para(stt)
#end
)

或是的话

2018-10-18 16:06

public class ParaInDirective extends Directive {


/**
* 描述:
*/
private int index = -1;

/**
* 描述:
*
* @param exprList
* @author
* @created 2017年7月7日 下午2:57:23
* @see Directive#setExprList(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;
}

@Override
public void exec(Env env, Scope scope, com.jfinal.template.io.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());
}

}

糊搞

2018-10-19 00:22

@或是的话 强,,,我刚写到一半你这就有现成的了,,,谢了,在下直接拿来使用了。。。

casey123

2019-05-08 17:06

@jfinal009 x怎么传进去的?

chcode

2021-03-05 11:45

使用 模版函数就行了 #@in(list)

#define in(values)
in (
#for(x:values)
#para(x)#(for.last?'':',')
#end
)
#end

fmpoffice

2022-02-22 16:36

@chcode 谢谢回复指点:
List list=new ArrayList<>();
list.add("a");
list.add("b");
Kv kv=Kv.by("list",list);
Db.template("sqlkey",kv);
模版:
select * from test where a #@in(list)

最终sql:
select * from test where a in ('a','b');

热门分享

扫码入社