简体   繁体   中英

Persist Only Changed Fields

I have an application which gets data from a database (Mongo) when a user connects, and saves it when a user disconnects and at fixed intervals to reduce the likelihood of data loss if a server goes down. I am using data access objects to save users to the database which updates every field regardless of if it has been changed. This can lead to problems such as when a user joins multiple servers and makes changes on one of them but the changes are overwritten when the user disconnects from another.

Are there any established ways of persisting only modified fields or any frameworks that do this? I would rather not use a boolean for every field as I have many fields inside the User object and adding a dirty flag to each of them would increase the class size dramatically.

The steps your application takes:

  1. User gets data from MongoDB

  2. This data get's partially modified

  3. The modifications should get saved

This means: The part of your application that modifies the data should take care of that.


The Spring team introduces some Diff tool, a few months ago: https://spring.io/blog/2014/10/22/introducing-spring-sync

Using that, you'll get a Patch object, which only contains the changes.

Patch patch = Diff.diff(original, modified);

Here's an approach that might work:

  1. Object data = mongoClient.getData();
  2. Object modifiedData = modify(data);
  3. Patch patch = Diff.diff(data, modifiedData);

The patch now contains everything that has changed. Now you must somehow use the internals of the Patch object and map that to MongoDB's $set commands.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM