mysql template sql_sqlTemplate的使用

不断学习,不断进步。

在纯jfinal项目里面变成了这样:###组装条件语句

#define whereSqlTemplate()

#for(x : cond)  ###处理条件cond参数

and

#if(x.key.contains(" in"))  ###拼装in条件

#(x.key) #("(") #for(inVal : x.value.split(",")) #(for.index == 0 ? "" : ",")#para(inVal) #end #(")")

#else  ###拼装其余条件,= > = <= != and

#(x.key) #para(x.value)

#end

#end

#end

###测试

#sql("test")

select * from

#if(isBak??=="001")

log_bak

#else

log

#end

where 1=1

#@whereSqlTemplate()

#(orderSql??)

#end/**

* 构建DbTemplate(BaseController中的方法)

* @param sqlId       sql模板中的id

* @param cond        查询条件

* @param defOrderSql 默认排序,表格有排序时不生效

* @param otherInfo   sql中其他

* @return

*/

private static DbTemplate buildDbTemplate(String sqlId, Kv cond, String orderSql, Kv otherInfoKv) {

DbPro dbPro = Db.use();

// 排序参数

if (StrKit.notBlank(orderSql)) {

orderSql = " order by " + orderSql.toUpperCase().replace("ORDER BY", "");

}

Kv data = Kv.by("cond", cond);

data.set("orderSql", orderSql);

data.set(otherInfoKv);

return dbPro.template(sqlId, data);

}

Controller中调用:

Kv cond = Kv.by("id=", get("id"));

KvotherInfoKv = Kv.by("isBak", "002");

DbTemplate dbTemplate = buildDbTemplate("test", cond,"order by id",otherInfoKv);

dbTemplate.paginate(pageNumber, pageSize);

dbTemplate.findFirst();

——————————2020.9.4——————————

之前一直是sql模板文件里写一部分拼装sql 的逻辑,又在controller里也写一段拼装sql的逻辑。

这样不仅导致维护起来麻烦,还让sql模板变得臃肿(每个sql都得写一遍重复的逻辑代码)。

今天仔细研究了一下文档,结合波总在【Jfinal 如何实现IN查询呢????】反馈中回复的信息,整理了一下之前的代码。

###使用sql模板进行条件拼装

#sql("templateSql")

#(querySql)  ###查询使用的sql

#for(x : cond)  ###处理条件cond参数

#(for.first ? "where": "and")

#if(x.key.contains(" like"))  ###拼装like条件

#(x.key) concat('%', #para(x.value), '%')

#elseif(x.key.contains(" in"))  ###拼装in条件

#(x.key) #("(")

#for(inVal : x.value.split(","))

#(for.index == 0 ? "" : ",")#para(inVal)

#end

#(")")

#else  ###拼装其余条件,= > = <= != and

#(x.key) #para(x.value)

#end

#end

#(orderSql??)

#end

#sql("yourSqlId")

select * from blog

#endKv kv = Kv.create();

kv.set("querySql", Db.getSql("yourSqlId"));

kv.set("orderSql", "order by id");

// 组装查询条件

Kv condKv = Kv.create();

condKv.set("title like", "test");

condKv.set("title in", "test 1");

kv.set("cond", condKv);

SqlPara sp = Db.getSqlPara("templateSql", kv);

System.out.println("=================");

System.out.println(Db.find(sp));

System.out.println(Db.paginate(1, 3, sp));

System.out.println("=================");

System.out.println(new Blog().find(sp));

System.out.println(new Blog().paginate(2, 3, sp));

System.out.println("=================");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值