I would like to automatically handle optimistic lock exceptions through user defined merge policies however while testing my logic in a simple test case I encounter an exception when committing the transaction. If a merge fails are you not able to attempt to merge again in the same transaction?
javax.persistence.RollbackException: Transaction rolled back because transaction was set to RollbackOnly.
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:92)
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:63)
EntityManager em = createEntityManager();
try {
em.getTransaction().begin();
mergeInstance(em, entity_b);
em.getTransaction().commit();
} catch (Exception p) {
Assert.fail(p.getMessage());
} finally {
if (em.isOpen()) {
em.close();
}
}
private void mergeInstance(EntityManager em, InstanceImpl entity) {
int retryCount = 2;
int cnt = 0;
InstanceImpl localEntity = entity;
while (cnt < retryCount) {
try {
localEntity = em.merge(localEntity);
return;
} catch (OptimisticLockException e) {
cnt++;
System.out.println("\n>>> Optimistic Lock Exception encountered, retry number "+cnt);
String sql = "SELECT e FROM InstanceImpl e WHERE e.uuid IN ('" //$NON-NLS-1$
+ localEntity.getUUID().toString() + "')"; //$NON-NLS-1$
Query query = em.createQuery(sql);
query.setHint(QueryHints.CACHE_USAGE, CacheUsage.DoNotCheckCache);
// Merge local data with latest repository data
InstanceImpl repoEntity = (InstanceImpl)query.getSingleResult();
localEntity.setOptLock(repoEntity.getOptLock());
}
}
}
--

Dennis Fuglsang | Consulting Member Technical Staff
Phone: +1 314 682 0497 | Mobile: +1 314 607 8087
Oracle Oracle SOA Governance - Enterprise Repository
424 South Woods Mill Road | Chesterfield, MO 63017

| Oracle is committed to developing practices and products that help protect the environment |