Tato
Tato

Reputation: 195

How to lock a database row with JPA

In the following code snippet, the whole table is locked instead of a single row:

@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void myInsertMethod(MyEntity myEntity) {

         
    /*1 this doesn't works*/
         manager.lock(myEntity,LockModeType.READ);
         manager.persist(myEntity);
    
    /* and this works but I dont know is it what i want or not...*/
        manager.persist(myEntity);
        manager.lock(myEntity,LockModeType.READ);
         
    }   

I think that the correct code will be the following, but it doesn't work

/*lock entire table for select*/
manager.lock(MyEntity.class.LockModeType.READ);
/* and after locking table persist code */
manager.persist(myEntity);

Please tell me how I can do this job and suggest me a good article for learning this issue.

Upvotes: 2

Views: 10379

Answers (1)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 154120

The LockModeType.READ is equals to OPTIMISTIC, meaning Hibernate tries to verify the optimistically locked entity version before transaction completion.

Aside from the possible race condition, this won't help you too much. In your case, the entity acquires an implicit lock when the flush operation issues an INSERT statement.

Because entities have unique PRIMARY KEYS, you shouldn't even care too much about locking the rows, since you can't have two transactions inserting the same row. The concurrency control is more suitable for UPDATE/DELETE statements, and even then, you don't need to lock an entire table (just the records you want to change).

Upvotes: 2

Related Questions