2

In application which I'm currently developing I have data structure:

 Bucket [1] ------ [Many] Element 

Now I have view when I can add remove and modify elements. Now i have situation when multiple user are editing same bucket, and they can messed up other's edit. I want to solve this problem by checking and updating bucket version each time when data is saved.

JPA has own version, so I plan to reuse that. But JPA willingly does not updates Bucket version when its element was updated. Is there a good way how to enforce version update on entity in JPA?

Currently I found some suggestion, like create dummy field, have own version field, or detaching and merging entity. Non of them seems right to me, is it anything better?

I'm using eclipse link with spring data if this helps.

4
  • I have already used the version in JPA and it's updated automatically : it's the point of that feature: You need to annotate the field (long type) with @Version. If the version is not the good one, an exception is thrown and the last transaction is canceled. Don't forget to use optimist locking to avoid locking field on database during a long amount of time. Commented Oct 29, 2015 at 16:23
  • if many users are editing at same field there's gonna be some data corruption. do your users have preferable rating? Commented Oct 29, 2015 at 16:23
  • @nafas user dealt with dto, not with entities, and it is happened outside of transaction. so there is no problem with data corruption. and no user does not have any ratings. whoever saves first, he suceed, preventing others from saving Commented Oct 29, 2015 at 16:31
  • @rlm thanks, but i already know that, what i nees is to update version on bucket when user do change on element Commented Oct 29, 2015 at 16:34

1 Answer 1

5

You can use OPTIMISTIC_FORCE_INCREMENT locking to force an update to your Bucket entity when the relationship is changed (i.e. adding and removing elements in your one-to-many collections object). This will cause any updates in any other persistence contexts to fail if they make changes without knowing about the relationship update.

Example:

public void addElement(int bucketId, Element element) { Bucket bucket = em.find(Bucket.class, bucketId); em.lock(bucket, LockModeType.OPTIMISTIC_FORCE_INCREMENT); bucket.add(element); element.setBucket(bucket); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.