JFinal一行代碼搞定增刪改,要的就是快

一、拓展篇

首先需要重寫getModel方法,但是這有個問題,重寫之後的方法和getModel的參數有點衝突,所以選擇不重寫,另外寫個方法佔且叫getBaseModel吧,getBaseModel的實現如下

/**
 * 
 * @Description: 基礎類擴展,實現在一些快速的一步操作
 * @author lianghao
 * @date 2016年2月26日 下午3:02:04
 */
public class BaseController extends Controller {
    
   public <T extends Model<?>> T getBaseModel(Class<?> modelClass, String... removeParas) {
        T model = null;
        try {
            model = (T) modelClass.newInstance();
        } catch (Exception e) {
            logger.error("baseController init exception" + e);
        }
        Map<String, String[]> parasMap = getParaMap();
        Map<String, String> removeParasMap = new HashMap<String, String>();
        for (String para: removeParas) {
            removeParasMap .put(para, para);
        }
        for (Entry<String, String[]> e : parasMap.entrySet()) {
            if (removeParasMap.containsKey(e.getKey()))
                continue;
            if (e.getValue()[0] != null)
                model.set(reqParaFormat.paraToFormat(e.getKey()), e.getValue()[0]);

        }
        return model;
    }
}

這裏面有兩個方法去轉換參數格式,如果請求的參數是根據自己的需要實現不同的轉換,我這邊以請求的是駝峯轉成數據庫的大寫如userName轉成USER_NAME,具體的實現可以根據自己的需求做封裝,有了這個BaseModel增改就很方便了,擴展如下

public boolean save(Class<?> modelClass, String... keys){
      Model model = getBaseModel(modelClass, keys);
      return model.save();
}

public boolean update(Class<?> modelClass, String... keys){
      Model model = getBaseModel(modelClass, keys);
      return model.update();
}
/**
必須傳入主鍵id
**/
public boolean delete(Class<?> modelClass, String... keys){
      Model model = getBaseModel(modelClass, keys);
      return model.delete();
}

這樣就搞定了

使用篇

完成了上面的擴展,使用時,只要把你的Controller繼成你的BaseController,就可以了,使用如下,一步增刪改

/**
後面參數加入不屬於這個表的參數過濾,如果沒有就不加
**/
save(User.class, "test");
update(User.class);
delete(User.class);

又節省了你的開發時間,只需一行代碼就搞定了增刪改,媽媽再也不用擔心我的學習

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章