Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8680139
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T21:10:10+00:00 2026-06-12T21:10:10+00:00

I have searched through the posts in stackoverflow and I hope this is not

  • 0

I have searched through the posts in stackoverflow and I hope this is not a duplicate.

I am trying my hands on Optimistic locking for the first time, I am able to do it with spring managed LockModeType, but unable to define the LockMode myself

Following is the code example:

I am injecting persistence context using:

@PersistenceContext
private EntityManager entityManager;

1st approach: Using annotational transaction

@Transactional
    public void updateUserProfile(UserProfile userProfile) {
        entityManager.lock(userProfile, LockModeType.OPTIMISTIC); // 1*
        entityManager.merge(userProfile);
    }

Exception at 1: java.lang.IllegalArgumentException: entity not in the persistence context

2nd approach: Managing transaction

public void updateUserProfile(UserProfile userProfile) {
        entityManager.getTransaction().begin(); // 2*
        entityManager.lock(userProfile, LockModeType.OPTIMISTIC); 
        entityManager.merge(userProfile);
        entityManager.getTransaction().commit();
    }

Exception at 2: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead

3rd approach: Since I got exception with shared entityManager, I also tried creating EntityManager from entityManagerFactory.

@Transactional
public void updateUserProfile(UserProfile userProfile) {
        EntityManager em = entityManager.getEntityManagerFactory().createEntityManager();
        em.getTransaction().begin();
        em.lock(userProfile, LockModeType.OPTIMISTIC);  // 3*
        em.merge(userProfile);
        em.getTransaction().commit();
    }

Exception at 3: entity not in the persistence context

In my application context, I am using org.springframework.orm.jpa.JpaTransactionManager for defining transactionManager and org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean for defining entityManagerFactory

Thanks in advance!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T21:10:11+00:00Added an answer on June 12, 2026 at 9:10 pm

    Conditions for locking a JPA entity:

    1. you must be within a transactional context
    2. the entity must be in a managed state (i.e. active within a persistence context.

    You seem to be violating (2) – attempt to lock detached entity.

    You could merge() earlier.

    Important Points:

    • If you modify an entity and run a transaction, and you have a version attribute in the entity, marked with @Version, then optimistic locking is automatically carried out at the granularity of the entity. The version attribute is updated and if it hasn’t already changed in the DB, then the write succeeds. This is the common simple locking case, where all writes to an individual entity are serialised to avoid corruption. If each entity/record can be treated independently, no need to set any LockMode as this is default behaviour. Have a close look at this option – I suspect this matches your simple requirements.

    • If you have more complex processing and need to carry out reads or writes across a number of logically related entity instances, as a consistent coherent atomic operation, with all other writes blocked/isolated for the duration – then you need to set your own lock mode, as automated individual per-entity locks won’t work. You need to carefully design the set of entities that are read or written in a coherent fashion and manually design and implement your own manual locking solution- possibly picking a top-most entity in a relationship hierarchy to record the “global” lock for all the related ‘child’ entities (leveraging its @Version attribute).

    • Any manual locking solution requires all DB writing logic to honour the lock. This means that other transactions that operate on the same entities, must understand your locking design and in fact, must attempt to take out your lock before writing. A lock which doesn’t cause various writes to block and serialise is in fact no lock at all.

    • For optimistic locking, the exact timing for taking out the lock is flexible. The lock is not checked and written to the DB until the commit & flush operation occurs. So you can take out the lock any time from the start of the tx to the commit. For pessimistic locking the opposite is true – you must guard the critical region(s) of code as if your life depends on it. Usually pessimistic lockMode should be set as part of a em.find() or em.query that starts of the transaction – or if this is not possible because managed objects are already in memory, then you should do a em.flush() and em.refresh(PESSIMISTIC_WRITE)

    =:-)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have searched through many times but have not seen this before. Probably really
I have searched through all the similar posts and google and have not quite
I have been trying various implementations to make this work, and have searched StackOverflow
Im trying to translate an object without using glTranslate(). I have searched through web
I have searched through the numerous S/O postings and have not found an answer
This is my first post so I hope I am not violating any rules.
I realize this is a popular topic, and I've searched through many posts here
I've searched through many posts on stackoverflow for an answer, and prehaps I'm just
I have searched through internet & found that there are no any direct method
I have searched through the net and still have no clue how to do

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.