此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Data MongoDB 4.4.0spring-doc.cadn.net.cn

保存、更新和删除文档

MongoTemplate / ReactiveMongoTemplatge允许您保存、更新和删除域对象,并将这些对象映射到存储在 MongoDB 中的文档。 命令式 API 和反应式 API 的 API 签名基本相同,只是返回类型不同。 虽然同步 API 使用voidObjectList反应式对应物包括Mono<Void>,Mono<Object>Flux.spring-doc.cadn.net.cn

请考虑以下类:spring-doc.cadn.net.cn

public class Person {

	private String id;
	private String name;
	private int age;

	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
}

鉴于Person类,您可以保存、更新和删除对象,如下例所示:spring-doc.cadn.net.cn

public class MongoApplication {

  private static final Log log = LogFactory.getLog(MongoApplication.class);

  public static void main(String[] args) {

    MongoOperations template = new MongoTemplate(new SimpleMongoClientDbFactory(MongoClients.create(), "database"));

    Person p = new Person("Joe", 34);

    // Insert is used to initially store the object into the database.
    template.insert(p);
    log.info("Insert: " + p);

    // Find
    p = template.findById(p.getId(), Person.class);
    log.info("Found: " + p);

    // Update
    template.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class);
    p = template.findOne(query(where("name").is("Joe")), Person.class);
    log.info("Updated: " + p);

    // Delete
    template.remove(p);

    // Check that deletion worked
    List<Person> people =  template.findAll(Person.class);
    log.info("Number of people = : " + people.size());


    template.dropCollection(Person.class);
  }
}

前面的示例将生成以下日志输出(包括来自MongoTemplate):spring-doc.cadn.net.cn

DEBUG apping.MongoPersistentEntityIndexCreator:  80 - Analyzing class class org.spring.example.Person for index information.
DEBUG work.data.mongodb.core.MongoTemplate: 632 - insert Document containing fields: [_class, age, name] in collection: person
INFO               org.spring.example.MongoApp:  30 - Insert: Person [id=4ddc6e784ce5b1eba3ceaf5c, name=Joe, age=34]
DEBUG work.data.mongodb.core.MongoTemplate:1246 - findOne using query: { "_id" : { "$oid" : "4ddc6e784ce5b1eba3ceaf5c"}} in db.collection: database.person
INFO               org.spring.example.MongoApp:  34 - Found: Person [id=4ddc6e784ce5b1eba3ceaf5c, name=Joe, age=34]
DEBUG work.data.mongodb.core.MongoTemplate: 778 - calling update using query: { "name" : "Joe"} and update: { "$set" : { "age" : 35}} in collection: person
DEBUG work.data.mongodb.core.MongoTemplate:1246 - findOne using query: { "name" : "Joe"} in db.collection: database.person
INFO               org.spring.example.MongoApp:  39 - Updated: Person [id=4ddc6e784ce5b1eba3ceaf5c, name=Joe, age=35]
DEBUG work.data.mongodb.core.MongoTemplate: 823 - remove using query: { "id" : "4ddc6e784ce5b1eba3ceaf5c"} in collection: person
INFO               org.spring.example.MongoApp:  46 - Number of people = : 0
DEBUG work.data.mongodb.core.MongoTemplate: 376 - Dropped collection [database.person]
public class ReactiveMongoApplication {

  private static final Logger log = LoggerFactory.getLogger(ReactiveMongoApplication.class);

  public static void main(String[] args) throws Exception {

    CountDownLatch latch = new CountDownLatch(1);

    ReactiveMongoTemplate template = new ReactiveMongoTemplate(MongoClients.create(), "database");

    template.insert(new Person("Joe", 34)).doOnNext(person -> log.info("Insert: " + person))
      .flatMap(person -> template.findById(person.getId(), Person.class))
      .doOnNext(person -> log.info("Found: " + person))
      .zipWith(person -> template.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class))
      .flatMap(tuple -> template.remove(tuple.getT1())).flatMap(deleteResult -> template.findAll(Person.class))
      .count().doOnSuccess(count -> {
        log.info("Number of people: " + count);
        latch.countDown();
      })

      .subscribe();

    latch.await();
  }
}

MongoConverter导致String以及一个ObjectId通过识别(通过约定)存储在数据库中的Idproperty name 属性。spring-doc.cadn.net.cn

前面的示例旨在演示如何对MongoTemplate / ReactiveMongoTemplate而不是显示复杂的映射功能。 前面示例中使用的查询语法在 “查询文档” 一节中有更详细的说明。spring-doc.cadn.net.cn

MongoDB 要求您有一个_id字段。请参阅 ID 处理部分,了解有关此字段的特殊处理的详细信息。
MongoDB 集合可以包含表示各种类型实例的文档。有关详细信息,请参阅类型映射

插入 / 保存

有几种方便的方法MongoTemplate用于保存和插入对象。 要对转换过程进行更精细的控制,可以使用MappingMongoConverter— 例如Converter<Person, Document>Converter<Document, Person>.spring-doc.cadn.net.cn

插入作和保存作之间的区别在于,如果对象尚不存在,则保存作将执行插入。

使用 save作的简单情况是保存一个 POJO。 在这种情况下,集合名称由类的名称(非完全限定)确定。 您还可以使用特定的集合名称调用 save作。您可以使用映射元数据覆盖用于存储对象的集合。spring-doc.cadn.net.cn

插入或保存时,如果Id属性,则假设其值将由数据库自动生成。 因此,为了自动生成ObjectId要成功,需要Idproperty 或 field 必须是StringObjectIdBigInteger.spring-doc.cadn.net.cn

以下示例显示如何保存文档并检索其内容:spring-doc.cadn.net.cn

使用 MongoTemplate 插入和检索文档
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Criteria.query;

//...

template.insert(new Person("Bob", 33));

Person person = template.query(Person.class)
    .matching(query(where("age").is(33)))
    .oneValue();
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Criteria.query;

//...

Mono<Person> person = mongoTemplate.insert(new Person("Bob", 33))
    .then(mongoTemplate.query(Person.class)
        .matching(query(where("age").is(33)))
        .one());

可以使用以下 insert 和 save作:spring-doc.cadn.net.cn

也可以使用一组类似的 insert作:spring-doc.cadn.net.cn

如何_idField 在 Mapping Layer 中处理

MongoDB 要求您有一个_id字段。 如果您不提供,驱动程序会分配一个ObjectId替换为生成的值,而不考虑您的域模型,因为服务器不知道您的标识符类型。 当您使用MappingMongoConverter中,某些规则控制 Java 类中的属性如何映射到 this_id田:spring-doc.cadn.net.cn

  1. 带有@Id (org.springframework.data.annotation.Id) 映射到_id田。spring-doc.cadn.net.cn

  2. 没有注释但名为id映射到_id田。spring-doc.cadn.net.cn

下面概述了对映射到_iddocument 字段(使用MappingMongoConverter(默认值MongoTemplate).spring-doc.cadn.net.cn

  1. 如果可能,请使用id声明为String转换为 Java 类并存储为ObjectId通过使用 SpringConverter<String, ObjectId>.有效的转换规则将委托给 MongoDB Java 驱动程序。如果无法转换为ObjectId,则该值将作为字符串存储在数据库中。spring-doc.cadn.net.cn

  2. id声明为BigInteger转换为 Java 类并存储为ObjectId通过使用 SpringConverter<BigInteger, ObjectId>.spring-doc.cadn.net.cn

如果 Java 类中不存在前几组规则中指定的字段或属性,则隐式的_idfile 由驱动程序生成,但未映射到 Java 类的属性或字段。spring-doc.cadn.net.cn

在查询和更新时,MongoTemplate使用与上述规则对应的转换器来保存文档,以便查询中使用的字段名称和类型可以匹配域类中的内容。spring-doc.cadn.net.cn

某些环境需要自定义的映射方法Id值,例如存储在 MongoDB 中的数据,这些数据未通过 Spring Data 映射层运行。文档可以包含_id值,可以表示为ObjectIdString. 将文档从存储读取回域类型工作正常。通过其id可能由于隐式的ObjectId转换。因此,无法以这种方式检索文档。 对于这些情况@MongoId提供对实际 ID 映射尝试的更多控制。spring-doc.cadn.net.cn

示例 1.@MongoId映射
public class PlainStringId {
  @MongoId String id; (1)
}

public class PlainObjectId {
  @MongoId ObjectId id; (2)
}

public class StringToObjectId {
  @MongoId(FieldType.OBJECT_ID) String id; (3)
}
1 id 被视为String无需进一步转换。
2 id 被视为ObjectId.
3 id 被视为ObjectId如果给定的String是有效的ObjectIdhex 的 API API 中,否则为String.对应于@Id用法。

我的文档将保存到哪个集合中?

有两种方法可以管理用于文档的集合名称。 使用的默认集合名称是更改为以小写字母开头的类名。 所以一个com.test.Person类存储在person收集。 您可以通过在@Document注解。 您还可以通过提供自己的集合名称作为所选MongoTemplate方法调用。spring-doc.cadn.net.cn

插入或保存单个对象

MongoDB 驱动程序支持在单个作中插入文档集合。 以下方法在MongoOperationsinterface 支持此功能:spring-doc.cadn.net.cn

  • insert:插入对象。如果存在具有相同id,则生成错误。spring-doc.cadn.net.cn

  • insertAll:采用Collectionof objects 作为第一个参数。此方法根据前面指定的规则检查每个对象并将其插入到相应的集合中。spring-doc.cadn.net.cn

  • save:保存对象,覆盖可能具有相同id.spring-doc.cadn.net.cn

在批处理中插入多个对象

MongoDB 驱动程序支持在一个作中插入文档集合。 以下方法在MongoOperations接口通过以下方式支持此功能insert或专用的BulkOperations接口。spring-doc.cadn.net.cn

批量插入
Collection<Person> inserted = template.insert(List.of(...), Person.class);
Flux<Person> inserted = template.insert(List.of(...), Person.class);
批量插入
BulkWriteResult result = template.bulkOps(BulkMode.ORDERED, Person.class)
    .insert(List.of(...))
    .execute();
Mono<BulkWriteResult> result = template.bulkOps(BulkMode.ORDERED, Person.class)
    .insert(List.of(...))
    .execute();

批处理和批量的服务器性能相同。 但是,批量作不会发布生命周期事件spring-doc.cadn.net.cn

任何@Version在调用 Insert 之前未设置的属性将自动初始化为1(对于像int) 或0对于包装器类型(例如。Integer).
在 参见 乐观锁定 部分阅读更多内容。
spring-doc.cadn.net.cn

更新

对于更新,您可以使用MongoOperation.updateFirst或者,您可以使用MongoOperation.updateMultimethod 或all在 Fluent API 上。 以下示例显示了所有SAVINGS我们将使用$inc算子:spring-doc.cadn.net.cn

使用MongoTemplate / ReactiveMongoTemplate
import static org.springframework.data.mongodb.core.query.Criteria.where;
import org.springframework.data.mongodb.core.query.Update;

// ...

UpdateResult result = template.update(Account.class)
    .matching(where("accounts.accountType").is(Type.SAVINGS))
    .apply(new Update().inc("accounts.$.balance", 50.00))
    .all();
import static org.springframework.data.mongodb.core.query.Criteria.where;
import org.springframework.data.mongodb.core.query.Update;

// ...

Mono<UpdateResult> result = template.update(Account.class)
    .matching(where("accounts.accountType").is(Type.SAVINGS))
    .apply(new Update().inc("accounts.$.balance", 50.00))
    .all();

除了Query前面讨论过,我们通过使用Update对象。 这Updateclass 具有与可用于 MongoDB 的更新修饰符匹配的方法。 大多数方法都会返回Updateobject 为 API 提供 Fluent 样式。spring-doc.cadn.net.cn

@Versionproperties 中未包含在Update将自动递增。 在 参见 乐观锁定 部分阅读更多内容。spring-doc.cadn.net.cn

运行文档更新的方法

  • updateFirst:使用更新的文档更新与查询文档条件匹配的第一个文档。spring-doc.cadn.net.cn

  • updateMulti:使用更新的文档更新与查询文档条件匹配的所有对象。spring-doc.cadn.net.cn

updateFirst不支持排序。请使用 findAndModify 申请Sort.
更新作的索引提示可以通过以下方式提供Query.withHint(…​).

Methods 中的Update

你可以用一点 “'syntax sugar'” 和Updateclass 的 API 中,因为它的方法应该链接在一起。 此外,您可以启动创建新的Update实例public static Update update(String key, Object value)以及使用静态导入。spring-doc.cadn.net.cn

Updateclass 包含以下方法:spring-doc.cadn.net.cn

  • Update addToSet (String key, Object value)使用 Update using the update$addToSet更新修饰符spring-doc.cadn.net.cn

  • Update 当前日期 (String key)使用 Update using the update$currentDate更新修饰符spring-doc.cadn.net.cn

  • Update 当前时间戳 (String key)使用 Update using the update$currentDateupdate 修饰符替换为$type timestampspring-doc.cadn.net.cn

  • Update 公司 (String key, Number inc)使用 Update using the update$inc更新修饰符spring-doc.cadn.net.cn

  • Update 麦克斯 (String key, Object max)使用 Update using the update$max更新修饰符spring-doc.cadn.net.cn

  • Update 分钟 (String key, Object min)使用 Update using the update$min更新修饰符spring-doc.cadn.net.cn

  • Update (String key, Number multiplier)使用 Update using the update$mul更新修饰符spring-doc.cadn.net.cn

  • Update 流行 (String key, Update.Position pos)使用 Update using the update$pop更新修饰符spring-doc.cadn.net.cn

  • Update (String key, Object value)使用 Update using the update$pull更新修饰符spring-doc.cadn.net.cn

  • Update 拉全部 (String key, Object[] values)使用 Update using the update$pullAll更新修饰符spring-doc.cadn.net.cn

  • Update (String key, Object value)使用 Update using the update$push更新修饰符spring-doc.cadn.net.cn

  • Update 全部 (String key, Object[] values)使用 Update using the update$pushAll更新修饰符spring-doc.cadn.net.cn

  • Update 重命名 (String oldName, String newName)使用 Update using the update$rename更新修饰符spring-doc.cadn.net.cn

  • Update 设置 (String key, Object value)使用 Update using the update$set更新修饰符spring-doc.cadn.net.cn

  • Update setOnInsert (String key, Object value)使用 Update using the update$setOnInsert更新修饰符spring-doc.cadn.net.cn

  • Update 未凝固的 (String key)使用 Update using the update$unset更新修饰符spring-doc.cadn.net.cn

某些更新修饰符(例如$push$addToSet,允许嵌套其他运算符。spring-doc.cadn.net.cn

// { $push : { "category" : { "$each" : [ "spring" , "data" ] } } }
new Update().push("category").each("spring", "data")

// { $push : { "key" : { "$position" : 0 , "$each" : [ "Arya" , "Arry" , "Weasel" ] } } }
new Update().push("key").atPosition(Position.FIRST).each(Arrays.asList("Arya", "Arry", "Weasel"));

// { $push : { "key" : { "$slice" : 5 , "$each" : [ "Arya" , "Arry" , "Weasel" ] } } }
new Update().push("key").slice(5).each(Arrays.asList("Arya", "Arry", "Weasel"));

// { $addToSet : { "values" : { "$each" : [ "spring" , "data" , "mongodb" ] } } }
new Update().addToSet("values").each("spring", "data", "mongodb");

聚合管道更新

Update 方法公开MongoOperationsReactiveMongoOperations通过AggregationUpdate. 用AggregationUpdate允许在更新作中利用 MongoDB 4.2 聚合。 在更新中使用聚合允许通过使用单个作表示多个阶段和多个条件来更新一个或多个字段。spring-doc.cadn.net.cn

更新可以包括以下阶段:spring-doc.cadn.net.cn

示例 2.更新聚合
AggregationUpdate update = Aggregation.newUpdate()
    .set("average").toValue(ArithmeticOperators.valueOf("tests").avg())     (1)
    .set("grade").toValue(ConditionalOperators.switchCases(                 (2)
        when(valueOf("average").greaterThanEqualToValue(90)).then("A"),
        when(valueOf("average").greaterThanEqualToValue(80)).then("B"),
        when(valueOf("average").greaterThanEqualToValue(70)).then("C"),
        when(valueOf("average").greaterThanEqualToValue(60)).then("D"))
        .defaultTo("F")
    );

template.update(Student.class)                                              (3)
    .apply(update)
    .all();                                                                 (4)
db.students.update(                                                         (3)
   { },
   [
     { $set: { average : { $avg: "$tests" } } },                            (1)
     { $set: { grade: { $switch: {                                          (2)
                           branches: [
                               { case: { $gte: [ "$average", 90 ] }, then: "A" },
                               { case: { $gte: [ "$average", 80 ] }, then: "B" },
                               { case: { $gte: [ "$average", 70 ] }, then: "C" },
                               { case: { $gte: [ "$average", 60 ] }, then: "D" }
                           ],
                           default: "F"
     } } } }
   ],
   { multi: true }                                                          (4)
)
1 第一$setstage 根据 tests 字段的平均值计算新的字段平均值
2 第 2 个$set阶段根据第一个聚合阶段计算的平均字段计算新的字段等级
3 该管道在 students 集合上运行,并使用Student对于聚合字段映射。
4 将更新应用于集合中的所有匹配文档。

Upsert

与执行updateFirst作中,您还可以执行upsert作,如果未找到与查询匹配的文档,则将执行 INSERT。 插入的文档是 query 文档和 update 文档的组合。 以下示例演示如何使用upsert方法:spring-doc.cadn.net.cn

UpdateResult result = template.update(Person.class)
  .matching(query(where("ssn").is(1111).and("firstName").is("Joe").and("Fraizer").is("Update"))
  .apply(update("address", addr))
  .upsert();
Mono<UpdateResult> result = template.update(Person.class)
  .matching(query(where("ssn").is(1111).and("firstName").is("Joe").and("Fraizer").is("Update"))
  .apply(update("address", addr))
  .upsert();
upsert不支持排序。请使用 findAndModify 申请Sort.

@Versionproperties 中未包含在Update将自动初始化。 在 参见 乐观锁定 部分阅读更多内容。spring-doc.cadn.net.cn

替换集合中的文档

各种replace方法可通过MongoTemplateallow 覆盖第一个匹配的 Document。 如果未找到匹配项,则可以更新插入新的匹配项(如上一节所述),方法是提供ReplaceOptions与根据配置。spring-doc.cadn.net.cn

替换一个
Person tom = template.insert(new Person("Motte", 21)); (1)
Query query = Query.query(Criteria.where("firstName").is(tom.getFirstName())); (2)
tom.setFirstname("Tom"); (3)
template.replace(query, tom, ReplaceOptions.none()); (4)
1 插入新文档。
2 用于标识要替换的单个文档的查询。
3 设置必须包含相同_id作为 existing 或 no_id完全。
4 运行 replace作。 .将一个替换为 upsert
Person tom = new Person("id-123", "Tom", 21) (1)
Query query = Query.query(Criteria.where("firstName").is(tom.getFirstName()));
template.replace(query, tom, ReplaceOptions.replaceOptions().upsert()); (2)
1 _id值,否则 MongoDB 将创建一个新的 Potentially 域类型不兼容ObjectId. 由于 MongoDB 无法识别您的域类型,因此任何@Field(targetType)提示,生成的ObjectId可能与您的域模型不兼容。
2 upsert如果未找到匹配项,则插入新文档

无法更改_id的现有文档替换为 REPLACE作。 上upsertMongoDB 使用 2 种方法来确定条目的新 ID: *这_id在查询中使用,如下所示{"_id" : 1234 }*这_id存在于替换文档中。 如果没有_id,MongoDB 将创建一个新的ObjectId对于文档。 如果使用的域类型idproperty 具有不同的类型,例如Long.spring-doc.cadn.net.cn

查找和修改

findAndModify(…)method 开启MongoCollection可以更新文档,并在单个作中返回旧文档或新更新的文档。MongoTemplate提供四个findAndModify采用QueryUpdate类并转换自Document到你的 POJOs:spring-doc.cadn.net.cn

<T> T findAndModify(Query query, Update update, Class<T> entityClass);

<T> T findAndModify(Query query, Update update, Class<T> entityClass, String collectionName);

<T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass);

<T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass, String collectionName);

以下示例插入一些Person对象添加到容器中,并执行findAndUpdate操作:spring-doc.cadn.net.cn

template.insert(new Person("Tom", 21));
template.insert(new Person("Dick", 22));
template.insert(new Person("Harry", 23));

Query query = new Query(Criteria.where("firstName").is("Harry"));
Update update = new Update().inc("age", 1);

Person oldValue = template.update(Person.class)
  .matching(query)
  .apply(update)
  .findAndModifyValue(); // oldValue.age == 23

Person newValue = template.query(Person.class)
  .matching(query)
  .findOneValue(); // newValye.age == 24

Person newestValue = template.update(Person.class)
  .matching(query)
  .apply(update)
  .withOptions(FindAndModifyOptions.options().returnNew(true)) // Now return the newly updated document when updating
  .findAndModifyValue(); // newestValue.age == 25

FindAndModifyOptionsmethod 允许您设置returnNew,upsertremove. 从前面的代码片段扩展的示例如下:spring-doc.cadn.net.cn

Person upserted = template.update(Person.class)
  .matching(new Query(Criteria.where("firstName").is("Mary")))
  .apply(update)
  .withOptions(FindAndModifyOptions.options().upsert(true).returnNew(true))
  .findAndModifyValue()

@Versionproperties 中未包含在Update将自动递增。 在 参见 乐观锁定 部分阅读更多内容。spring-doc.cadn.net.cn

查找和替换

替换整个Document通过其id使用save方法。 但是,这可能并不总是可行的。findAndReplace提供了一种替代方法,允许通过简单的查询来标识要替换的文档。spring-doc.cadn.net.cn

例 3.查找和替换文档
Optional<User> result = template.update(Person.class)      (1)
    .matching(query(where("firstame").is("Tom")))          (2)
    .replaceWith(new Person("Dick"))
    .withOptions(FindAndReplaceOptions.options().upsert()) (3)
    .as(User.class)                                        (4)
    .findAndReplace();                                     (5)
1 将 Fluent Update API 与给定的域类型一起使用,以映射查询和派生集合名称,或者只使用MongoOperations#findAndReplace.
2 针对给定域类型映射的实际匹配查询。提供sort,fieldscollation设置。
3 额外的可选钩子来提供默认值以外的选项,例如upsert.
4 用于映射作结果的可选投影类型。如果没有,则使用初始域类型。
5 触发实际处理。用findAndReplaceValue获取可为 null 的结果,而不是Optional.
请注意,更换件不得持有id本身作为id的现有Document将是 由商店本身结转到替代品。还要记住findAndReplace将仅替换第一个 document 匹配查询条件,具体取决于可能给定的排序顺序。

删除

您可以使用以下五种重载方法之一从数据库中删除对象:spring-doc.cadn.net.cn

template.remove(tywin, "GOT");                                              (1)

template.remove(query(where("lastname").is("lannister")), "GOT");           (2)

template.remove(new Query().limit(3), "GOT");                               (3)

template.findAllAndRemove(query(where("lastname").is("lannister"), "GOT");  (4)

template.findAllAndRemove(new Query().limit(3), "GOT");                     (5)
1 删除由其_id从关联的集合中。
2 GOT收集。
3 删除GOT收集。与 <2> 不同,要删除的文档由其_id、运行给定的查询、应用sort,limitskip选项,然后在单独的步骤中一次性删除所有选项。
4 GOT收集。与 <3> 不同,文档不会批量删除,而是逐个删除。
5 删除GOT收集。与 <3> 不同,文档不会批量删除,而是逐个删除。

乐观锁定

@Versionannotation 提供的语法类似于 MongoDB 上下文中的 JPA 语法,并确保更新仅应用于具有匹配版本的文档。 因此,将 version 属性的实际值添加到 update 查询中,如果另一个作同时更改了文档,则 update 不会产生任何影响。 在这种情况下,一个OptimisticLockingFailureException被抛出。 以下示例显示了这些功能:spring-doc.cadn.net.cn

@Document
class Person {

  @Id String id;
  String firstname;
  String lastname;
  @Version Long version;
}

Person daenerys = template.insert(new Person("Daenerys"));                            (1)

Person tmp = template.findOne(query(where("id").is(daenerys.getId())), Person.class); (2)

daenerys.setLastname("Targaryen");
template.save(daenerys);                                                              (3)

template.save(tmp); // throws OptimisticLockingFailureException                       (4)
1 最初插入文档。version设置为0.
2 加载刚刚插入的文档。version仍然0.
3 使用version = 0.将lastname和 bumpversion1.
4 尝试更新之前加载的文档,该文档仍然具有version = 0.作失败,并显示OptimisticLockingFailureException,作为当前version1.

仅对MongoTemplate请考虑并更改版本属性。请咨询MongoOperationsJava doc 了解详细信息。spring-doc.cadn.net.cn

Optimistic Locking 需要设置WriteConcernACKNOWLEDGED.否则OptimisticLockingFailureException可以静默吞咽。
从版本 2.2 开始MongoOperations还包括@Version属性。 要删除Document无需进行版本检查,请使用MongoOperations#remove(Query,…​)而不是MongoOperations#remove(Object).
从版本 2.2 开始,存储库在删除版本控制实体时检查确认删除的结果。 一OptimisticLockingFailureException如果无法通过CrudRepository.delete(Object).在这种情况下,版本已更改或同时删除了对象。用CrudRepository.deleteById(ID)绕过乐观锁定功能并删除对象,无论其版本如何。