日常控制层查询操作
实现思路:
1、写一个公共sql模板
#sql("selectByAttr") select * from #(tableName) #for(x : cond) #(for.index == 0 ? "where" : "and") #(x.key) = #para(x.value) #end #end
2、在baseController中封装(可参考该例封装在其他层)如下:
public abstract class SoJptController extends Controller { public Kv getKv(Model<?> model) { Set<Entry<String, Object>> entrySet = model._getAttrsEntrySet(); Kv kv = new Kv(); for (Entry<String, Object> entry : entrySet) { if (entry.getValue() != null && !entry.getValue().toString().equals("")) { kv.set(entry.getKey(), entry.getValue()); } } return Kv.by("cond", kv); } public Model<?> findFirstByModel(Model<?> model) { Table table = TableMapping.me().getTable(model.getClass()); return model.findFirst(Db.getSqlPara("selectByAttr", getKv(model).set("tableName", table.getName()))); } public List<?> findByModel(Model<?> model) { Table table = TableMapping.me().getTable(model.getClass()); return model.find(Db.getSqlPara("selectByAttr", getKv(model).set("tableName", table.getName()))); } }
更多好玩的用法,请前往 sojpt.com 了解 sojpt 脚手架源码