刚接触jfinal半个月,关于修改表格方法只找到了update,或者自己去拼sql,不知道大家有没有这个问题。实在没找到框架内的选择性修改table的方法,于是自己封装了一个,希望对大家有所帮助。可能jinal有类似方法,我没有发现,如果大家知道的话,可以评论里告我,万分感谢!封装完以后调用参数有两个:sql空间名namespace + 要修改的model。
sql模板的名称可以固定为updateByIdSelective,将这个名称定义为常量,可以方便调用。
1.定义sql模板
all.sql#define updateByIdSelective(table)
update #(table)
#for(x : cond)
#(for.index == 0 ? "set" : " , ") #(x.key) #para(x.value)
#end
where id = #(id)
#end
#namespace("merchant")
#include("merchant.sql")
#end
merchant.sql#sql("updateByIdSelective")
#@updateByIdSelective("merchant")
#end
2.ModelUtil工具类,将model转化为map,以方便获取sqlparapackage com.xd.common.utils;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.jfinal.plugin.activerecord.Model;
public class ModelUtil {
public static Map toUpdateMap(Model model) {
Map map = new HashMap();
Map result = new HashMap();
Set> _getAttrsEntrySet = model._getAttrsEntrySet();
Iterator> it = _getAttrsEntrySet.iterator();
while (it.hasNext()) {
Entry entry = it.next();
if (entry.getValue() != null) {
if ("id".equals(entry.getKey())) {
result.put(entry.getKey(), entry.getValue());
} else {
map.put(entry.getKey() + " = ", entry.getValue());
}
}
}
result.put("cond", map);
return result;
}
}
3.调用sql模板public boolean updateByIdSelective(Merchant merchant) {
SqlPara sqlPara = Db.getSqlPara("merchant.updateByIdSelective", ModelUtil.toUpdateMap(merchant));
try {
Db.update(sqlPara);
} catch (Exception e) {
return false;
}
return true;
}