3.10.3.2. Configuring Lock Levels at Runtime
At runtime, you can override the default lock levels through the FetchPlan interface described above.
At the beginning of each datastore transaction, OpenJPA initializes the EntityManager's fetch plan with the default lock levels and timeouts described in the previous section.
By changing the fetch plan’s locking properties, you can control how objects loaded at different points in the transaction are locked.
You can also use the fetch plan of an individual Query to apply your locking changes only to objects loaded through that Query.
public LockModeType getReadLockMode();
public FetchPlan setReadLockMode(LockModeType mode);
public LockModeType getWriteLockMode();
public FetchPlan setWriteLockMode(LockModeType mode);
long getLockTimeout();
FetchPlan setLockTimeout(long timeout);
Controlling locking through these runtime APIs works even during optimistic transactions.
At the end of the transaction, OpenJPA resets the fetch plan’s lock levels to none.
You cannot lock objects outside of a transaction.
import org.apache.openjpa.persistence.*;
...
EntityManager em = ...;
em.getTransaction().begin();
// load stock we know we're going to update at write lock mode
Query q = em.createQuery("select s from Stock s where symbol = :s");
q.setParameter("s", symbol);
OpenJPAQuery oq = OpenJPAPersistence.cast(q);
FetchPlan fetch = oq.getFetchPlan();
fetch.setReadLockMode(LockModeType.WRITE);
fetch.setLockTimeout(3000); // 3 seconds
Stock stock = (Stock) q.getSingleResult();
// load an object we don't need locked at none lock mode
fetch = OpenJPAPersistence.cast(em).getFetchPlan();
fetch.setReadLockMode(null);
Market market = em.find(Market.class, marketId);
stock.setPrice(market.calculatePrice(stock));
em.getTransaction().commit();