Spring data mongodb optimistic lock
•
Java
Spring data provides an optimistic lock implementation for mongodb:
The @Version annotation provides Syntax similar to that of JPA in the context of MongoDB and makes sure updates are only applied to documents with a matching version. Therefore,the actual value of the version property is added to the update query in such a way that the update does not have any effect if another operation altered the document in the meantime. In that case,an OptimisticLockingFailureException is thrown. The following example shows these features:
The @ version annotation is provided to identify the version. Saving, deleting and other operations will verify the version. If there is inconsistency, an optisticlockingfailureexception will be thrown
Let's take an example:
@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)
be careful:
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码