jfinal 乐观锁

canca8年前 (2016-07-22)JFinal383
继承Model类,实现自己的BaseModel,重写save()和update()方法,然后所有的Model都继承自BaseModel
/**   * 重写save方法   */  public boolean save() {   this.set(getTable().getPrimaryKey(), ToolUtils.getUuidByJdk(true)); // 设置主键值   if(getTable().hasColumnLabel("version")){ // 是否需要乐观锁控制    this.set("version"Long.valueOf(0)); // 初始化乐观锁版本号   }   return super.save();  }
/**   * 重写update方法   */  @SuppressWarnings("unchecked")  public boolean update() {   Table table = getTable();   String name = table.getName();   String pk = table.getPrimaryKey();      // 1.数据是否还存在   String sql = new StringBuffer("select version from ").append(name).append(" where ").append(pk).append(" = ? ").toString();   Model<M> modelOld = findFirst(sql , getStr("ids"));   if(null == modelOld){ // 数据已经被删除    throw new RuntimeException("数据库中此数据不存在,可能数据已经被删除,请刷新数据后在操作");   }      // 2.乐观锁控制   Set<String> modifyFlag = null;   try {    Field field = this.getClass().getSuperclass().getSuperclass().getDeclaredField("modifyFlag");    field.setAccessible(true);    Object object = field.get(this);    if(null != object){     modifyFlag = (Set<String>) object;    }    field.setAccessible(false);   } catch (NoSuchFieldException | SecurityException e) {    log.error("业务Model类必须继承BaseModel");    e.printStackTrace();    throw new RuntimeException("业务Model类必须继承BaseModel");   } catch (IllegalArgumentException | IllegalAccessException e) {    log.error("BaseModel访问modifyFlag异常");    e.printStackTrace();    throw new RuntimeException("BaseModel访问modifyFlag异常");   }   boolean versionModify = modifyFlag.contains("version");   if(versionModify && getTable().hasColumnLabel("version")){ // 是否需要乐观锁控制    Long versionDB = modelOld.getLong("version"); // 数据库中的版本号    Long versionForm = getLong("version"); // 表单中的版本号    if(!(versionForm > versionDB)){     throw new RuntimeException("表单数据版本号和数据库数据版本号不一致,可能数据已经被其他人修改,请重新编辑");    }   }      return super.update();  }
/**   * 获取表映射对象   *    * @return   */  public Table getTable() {   return TableMapping.me().getTable(getClass());  }
所有需要乐观锁控制的表都加上version字段,在更新数据的表单页面加上
<input type="hidden" name="version" value="${version + 1}">


发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。