在model的某个属性上添加@version注解,系统每次保存会自动给该属性值加1,保证数据没有脏写入.但实际使用中,发现使用不当,会导致该检查频繁报错.简单分析@version字段的自增机制.
调用repo*的save方法.最终会调用org.springframework.data.mongodb.repository.support.SimpleMongoRepository类的save方法.
- public <S extends T> S save(S entity) {
-
- Assert.notNull(entity, "Entity must not be null!");
- //isNew方法实现写在下面了.
- if (entityInformation.isNew(entity)) {
- /*
- * insert对version的处理比较简单,直接判定是否存在version注解,存在则设置version对应字段为0
- */
- mongoOperations.insert(entity, entityInformation.getCollectionName());
- } else {
- mongoOperations.save(entity, entityInformation.getCollectionName());
- }
-
- return entity;
- }
-
- /** 判断一下主键的值是否存在,存在返回false,反正为true.所以这里的判断是不严谨的,通过前台给设置主键Id的,就会走save,而不是insert了.*/
- public boolean isNew(T entity) {
-
- ID id = getId(entity);
- Class<ID> idType = getIdType();
-
- if (!idType.isPrimitive()) {
- return id =



