MongoRepository接口 save方法

MongoRepository接口 save方法

项目中一些页面资料是是使用 MongoDB进行存储,在编写接口的过程中,碰到XXXPageRepository(项目自定义类,继承了MongoRepository)的save方法。
MongoDB进行数据添加时有两种方法:

  • save方法
  • insert方法

区别:
 进行数据添加操作时,使用insert:方法,当主键在集合中存在时,不做任何处理, 抛异常
 使用save方法时,当主键在集合中存在时,会进行更新, 数据整体都会更新 ,新数据会替换掉原数据 ID 以外的所有数据。ID 不存在则新增一条数据
 进行数据添加操作时,save 方法需要遍历列表,一个个插入, 而 insert 方法是直接批量插入

save方法具体内容:

@Override
	public <S extends T> S save(S entity) {

		Assert.notNull(entity, "Entity must not be null!");

		//判断主键的值是否存在
		if (entityInformation.isNew(entity)) {
			mongoOperations.insert(entity, entityInformation.getCollectionName());
		} else {
			mongoOperations.save(entity, entityInformation.getCollectionName());
		}

		return entity;
	}
发布了49 篇原创文章 · 获赞 40 · 访问量 3535

猜你喜欢

转载自blog.csdn.net/xueguchen/article/details/104582201