3

I've been using MongoDB and Spring Boot. I created a small webapp and I seem to hit a bug. After I deploy my web app to EC2 and have everything set up, I try different scenarios. One is where me and my friend try to save the same object to the database. This should not be possible as in my code I have restricted it, so it would get an error. But somehow, if timed perfectly, we both can save the document. We use our method contains that checks if the document exists already but it seems to fail in this case.

    /**
     * @param id ID of the document we are looking for
     * @return true or false based on if the Doc with given ID exists
     */
    @Override
    public boolean contains(String id) {
        return eventModelRepo.findById(id).isPresent();
    }

Any advice on how to fix this would be appreciated.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Bhagyesh
  • 700
  • 10
  • 31
  • Can you share the rest of of the repository code as well as the service layer? – akortex Aug 05 '20 at 15:05
  • This maybe casused based on how you are saving data. Remember `save` and `insert` are 2 different types of actions performed on your DB. – jack Oct 07 '20 at 18:28

1 Answers1

0

You need to a use a @Transactional annotation to prevent concurrent write access to the database

https://stackoverflow.com/a/39829964/2588771

John Brandli
  • 110
  • 4
  • so all i need to do is add that annotation? – Bhagyesh Aug 05 '20 at 17:47
  • You should add it to the parent method for the entire method chain in your @repository class. So whatever method is calling contains and then calling the function to add the document should have that annotation. – John Brandli Aug 05 '20 at 18:37