0

I have an application where users can display and edit items in my database via a website. Now, to be sure there are no upcoming problems when two users edit the same item, I would like to prevent them from doing so. That means, the first user accessing the item can edit it and the rest could only view the item. But sadly, I have not clue how to properly implement this. Let's have a look at the setup first:

I have a controller that could look like this:

@RestController
@RequestMapping(value="/item")
public class ItemController {

    @Autowired 
    ItemService itemService;

    @GetMapping(value="/getItem/{item_id}")
    public ResponseEntity getItem(@PathVariable String item_id) {
        this.itemService.getItemById(item_id);
        return ResponseEntity.ok(HttpStatus.OK);
    }

}

Now when getItem is called, I know that a user accessed the item with the given item_id from the frontend. So I could simply build a List of "blocked" items in my Controller, that contain the elements and check if the getItem-method is called: "If item_id is in the list, return Access denied & redirect to a "view-only" component, else ok". But this seems to be quite a prone workaround and I cannot inmagine this is the way it is intended to be solved. Also I'd need to somehow remove the items from the list on a reliable way.

Is there a pattern or something like that that shows how this is to be solved?

I am using Spring-Boot and Angular 7, if that helps.

RĂ¼diger
  • 893
  • 5
  • 27
  • 56

1 Answers1

3

This is especially difficult to do for many reasons, including the ones you mentioned. What if you lock a row and the user with the lock just closes the browser? Then the row is locked forever. Or do you then run a nightly routine to clear all locks, but then no user can access the record until the next day, etc.

In general, this has been a problem since databases were invented, so you would think that a solution would have been found, but not that I know of. Normally I try to recommend ways to minimize this happening through business process, not software.

In the software, you could consider instead of locking, providing ways to further minimize the impact of multiple updates by retaining the timestamp. When a user gets a row and then posts to update it, the system would check that the timestamp is still the same. If so, it allows the update. If not, it would either have to reject the change, or be smart and attempt to determine how its data is different from the current data and merge values as best it can.

You can read more about this here: Optimistic vs. Pessimistic locking

DeborahK
  • 57,520
  • 12
  • 104
  • 129