下面列出了怎么用javax.persistence.OptimisticLockException的API类实例代码及写法,或者点击链接到github查看源代码。
@Test(expected = OptimisticLockException.class)
public void givenVersionedEntitiesWithLockByRefreshMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L);
em.refresh(student, LockModeType.OPTIMISTIC);
EntityManager em2 = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L);
em.refresh(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
student2.setName("RICHARD");
em2.persist(student2);
em2.getTransaction()
.commit();
em2.close();
student.setName("JOHN");
em.persist(student);
em.getTransaction()
.commit();
em.close();
}
@Test(expected = OptimisticLockException.class)
public void givenVersionedEntitiesWithLockByFindMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC);
EntityManager em2 = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
student2.setName("RICHARD");
em2.persist(student2);
em2.getTransaction()
.commit();
em2.close();
student.setName("JOHN");
em.persist(student);
em.getTransaction()
.commit();
em.close();
}
/**
* This {@link WebFragmentRegistrationBean} is equivalent to the
* {@code META-INF/web-fragment.xml} of the {@code admin-template.jar}.
*
* @return adminTemplateWebFragmentRegistrationBean
*/
@Bean
public WebFragmentRegistrationBean adminTemplateWebFragmentRegistrationBean() {
WebFragmentRegistrationBean bean = new WebFragmentRegistrationBean();
bean.getContextParams().put("primefaces.THEME", "admin");
bean.getErrorPages().add(new ErrorPage(HttpStatus.FORBIDDEN, "/403.xhtml"));
bean.getErrorPages().add(new ErrorPage(AccessDeniedException.class, "/403.xhtml"));
bean.getErrorPages().add(new ErrorPage(AccessLocalException.class, "/403.xhtml"));
bean.getErrorPages().add(new ErrorPage(HttpStatus.NOT_FOUND, "/404.xhtml"));
bean.getErrorPages().add(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.xhtml"));
bean.getErrorPages().add(new ErrorPage(Throwable.class, "/500.xhtml"));
bean.getErrorPages().add(new ErrorPage(ViewExpiredException.class, "/expired.xhtml"));
bean.getErrorPages().add(new ErrorPage(OptimisticLockException.class, "/optimistic.xhtml"));
bean.getListeners().add(AdminServletContextListener.class);
return bean;
}
@Test
public void testRetry() {
when(mockLifecycleRepository.save(any(LifecycleEntity.class)))
// first time throw an exception
.thenThrow(new ObjectOptimisticLockingFailureException(ApplicationEntity.class, "foobar"))
// second time throw another exception
.thenThrow(new OptimisticLockException("Oops"))
// third time thrwo another exception
.thenThrow(new DataIntegrityViolationException("Hoppla"))
// Last time succeed.
.thenReturn(lifecycle);
assertThat(service.saveLifecycle(application, version, lifecycle)).isSameAs(lifecycle);
verify(mockApplicationRepository, times(4)).findByName(eq("foobar"));
verify(mockVersionRepository, times(4)).findByName(eq("1.0"));
verify(mockLifecycleRepository, times(4)).save(any(LifecycleEntity.class));
}
public void onGlobalAppDataChange(String stateName) throws Exception {
if (StringUtils.isBlank(stateName)) {
logger.error("Invalid name for state:[" + stateName + "]");
throw new Exception("Invalid name for state:[" + stateName + "]");
} else {
try {
XXGlobalState globalState = findByStateName(stateName);
if (globalState == null) {
createGlobalStateForAppDataVersion(stateName);
} else {
updateGlobalStateForAppDataVersion(globalState, stateName);
}
} catch (OptimisticLockException | org.eclipse.persistence.exceptions.OptimisticLockException ole) {
logger.warn("One or more objects cannot be updated because it has changed or been deleted since it was last read. Unable to update GlobalState for state:[" + stateName + "] continuing...");
} catch (Exception exception) {
logger.warn("Cannot create/update GlobalState for state:[" + stateName + "] continuing...");
}
}
}
@Test(expected = OptimisticLockException.class)
public void givenVersionedEntitiesWithLockByLockMethod_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L);
em.lock(student, LockModeType.OPTIMISTIC);
EntityManager em2 = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L);
em.lock(student, LockModeType.OPTIMISTIC_FORCE_INCREMENT);
student2.setName("RICHARD");
em2.persist(student2);
em2.getTransaction()
.commit();
em2.close();
student.setName("JOHN");
em.persist(student);
em.getTransaction()
.commit();
em.close();
}
@Test
public void whenUpdatingNonExistingObject_thenStaleStateException() {
thrown.expect(isA(OptimisticLockException.class));
thrown
.expectMessage("Row was updated or deleted by another transaction");
thrown.expectCause(isA(StaleObjectStateException.class));
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
Product product1 = new Product();
product1.setId(15);
product1.setName("Product1");
session.update(product1);
transaction.commit();
} catch (Exception e) {
rollbackTransactionQuietly(transaction);
throw (e);
} finally {
closeSessionQuietly(session);
}
}
@Test(expected = OptimisticLockException.class)
public void givenVersionedEntities_whenConcurrentUpdate_thenOptimisticLockException() throws IOException {
EntityManager em = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student = em.find(OptimisticLockingStudent.class, 1L);
EntityManager em2 = getEntityManagerWithOpenTransaction();
OptimisticLockingStudent student2 = em2.find(OptimisticLockingStudent.class, 1L);
student2.setName("RICHARD");
em2.persist(student2);
em2.getTransaction()
.commit();
em2.close();
student.setName("JOHN");
em.persist(student);
em.getTransaction()
.commit();
em.close();
}
@Test
@SuppressWarnings("serial")
public void testConvertJpaPersistenceException() {
EntityNotFoundException entityNotFound = new EntityNotFoundException();
assertSame(JpaObjectRetrievalFailureException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass());
NoResultException noResult = new NoResultException();
assertSame(EmptyResultDataAccessException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass());
NonUniqueResultException nonUniqueResult = new NonUniqueResultException();
assertSame(IncorrectResultSizeDataAccessException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass());
OptimisticLockException optimisticLock = new OptimisticLockException();
assertSame(JpaOptimisticLockingFailureException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass());
EntityExistsException entityExists = new EntityExistsException("foo");
assertSame(DataIntegrityViolationException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass());
TransactionRequiredException transactionRequired = new TransactionRequiredException("foo");
assertSame(InvalidDataAccessApiUsageException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass());
PersistenceException unknown = new PersistenceException() {
};
assertSame(JpaSystemException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass());
}
@Test
public void testTranslateException() {
OptimisticLockException ex = new OptimisticLockException();
assertEquals(
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex).getCause(),
dialect.translateExceptionIfPossible(ex).getCause());
}
@Override
@Retry(times = 2, on = OptimisticLockException.class)
@Transactional
public void saveItem() {
incrementCalls();
LOGGER.info("Save Item!");
throw new OptimisticLockException("Save Item!");
}
@Test
@SuppressWarnings("serial")
public void testConvertJpaPersistenceException() {
EntityNotFoundException entityNotFound = new EntityNotFoundException();
assertSame(JpaObjectRetrievalFailureException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass());
NoResultException noResult = new NoResultException();
assertSame(EmptyResultDataAccessException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass());
NonUniqueResultException nonUniqueResult = new NonUniqueResultException();
assertSame(IncorrectResultSizeDataAccessException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass());
OptimisticLockException optimisticLock = new OptimisticLockException();
assertSame(JpaOptimisticLockingFailureException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass());
EntityExistsException entityExists = new EntityExistsException("foo");
assertSame(DataIntegrityViolationException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass());
TransactionRequiredException transactionRequired = new TransactionRequiredException("foo");
assertSame(InvalidDataAccessApiUsageException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass());
PersistenceException unknown = new PersistenceException() {
};
assertSame(JpaSystemException.class,
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass());
}
@Test
public void testTranslateException() {
OptimisticLockException ex = new OptimisticLockException();
assertEquals(
EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ex).getCause(),
dialect.translateExceptionIfPossible(ex).getCause());
}
@Override
public ErrorResponse toErrorResponse(OptimisticLockException cve) {
HashMap<String, Object> meta = new HashMap<>();
meta.put(META_TYPE_KEY, JPA_OPTIMISTIC_LOCK_EXCEPTION_TYPE);
ErrorData error = ErrorData.builder()
.setMeta(meta)
.setCode(ERROR_TYPE)
.setStatus(Integer.toString(HttpStatus.CONFLICT_409))
.setDetail(cve.getMessage())
.build();
return ErrorResponse.builder().setStatus(HttpStatus.CONFLICT_409).setSingleErrorData(error).build();
}
private void checkOptimisticLocking(Object entity, Resource resource) {
MetaAttribute versionAttr = jpaMeta.getVersionAttribute();
if (versionAttr != null) {
JsonNode versionNode = resource.getAttributes().get(versionAttr.getName());
if (versionNode != null) {
Object requestVersion = context.getTypeParser().parse(versionNode.asText(),
(Class) versionAttr.getType().getImplementationClass());
Object currentVersion = versionAttr.getValue(entity);
if (!currentVersion.equals(requestVersion)) {
throw new OptimisticLockException(
resource.getId() + " changed from version " + requestVersion + " to " + currentVersion);
}
}
}
}
@Test
public void testOptimisticLocking() {
ResourceRepository<VersionedEntity, Serializable> repo = client
.getRepositoryForType(VersionedEntity.class);
VersionedEntity entity = new VersionedEntity();
entity.setId(1L);
entity.setLongValue(13L);
VersionedEntity saved = repo.create(entity);
Assert.assertEquals(0, saved.getVersion());
saved.setLongValue(14L);
saved = repo.save(saved);
Assert.assertEquals(1, saved.getVersion());
saved.setLongValue(15L);
saved = repo.save(saved);
Assert.assertEquals(2, saved.getVersion());
saved.setLongValue(16L);
saved.setVersion(saved.getVersion() - 1);
try {
saved = repo.save(saved);
Assert.fail();
} catch (OptimisticLockException e) {
// ok
}
VersionedEntity persisted = repo.findOne(1L, new QuerySpec(VersionedEntity.class));
Assert.assertEquals(2, persisted.getVersion());
Assert.assertEquals(15L, persisted.getLongValue());
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, BookingDTO dto)
{
TypedQuery<Booking> findByIdQuery = em.createQuery("SELECT DISTINCT b FROM Booking b LEFT JOIN FETCH b.tickets LEFT JOIN FETCH b.performance WHERE b.id = :entityId ORDER BY b.id", Booking.class);
findByIdQuery.setParameter("entityId", id);
Booking entity;
try
{
entity = findByIdQuery.getSingleResult();
}
catch (NoResultException nre)
{
entity = null;
}
entity = dto.fromDTO(entity, em);
try
{
entity = em.merge(entity);
}
catch (OptimisticLockException e)
{
return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
}
return Response.noContent().build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, PerformanceDTO dto)
{
TypedQuery<Performance> findByIdQuery = em.createQuery("SELECT DISTINCT p FROM Performance p LEFT JOIN FETCH p.show WHERE p.id = :entityId ORDER BY p.id", Performance.class);
findByIdQuery.setParameter("entityId", id);
Performance entity;
try
{
entity = findByIdQuery.getSingleResult();
}
catch (NoResultException nre)
{
entity = null;
}
entity = dto.fromDTO(entity, em);
try
{
entity = em.merge(entity);
}
catch (OptimisticLockException e)
{
return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
}
return Response.noContent().build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, TicketCategoryDTO dto)
{
TypedQuery<TicketCategory> findByIdQuery = em.createQuery("SELECT DISTINCT t FROM TicketCategory t WHERE t.id = :entityId ORDER BY t.id", TicketCategory.class);
findByIdQuery.setParameter("entityId", id);
TicketCategory entity;
try
{
entity = findByIdQuery.getSingleResult();
}
catch (NoResultException nre)
{
entity = null;
}
entity = dto.fromDTO(entity, em);
try
{
entity = em.merge(entity);
}
catch (OptimisticLockException e)
{
return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
}
return Response.noContent().build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, EventCategoryDTO dto)
{
TypedQuery<EventCategory> findByIdQuery = em.createQuery("SELECT DISTINCT e FROM EventCategory e WHERE e.id = :entityId ORDER BY e.id", EventCategory.class);
findByIdQuery.setParameter("entityId", id);
EventCategory entity;
try
{
entity = findByIdQuery.getSingleResult();
}
catch (NoResultException nre)
{
entity = null;
}
entity = dto.fromDTO(entity, em);
try
{
entity = em.merge(entity);
}
catch (OptimisticLockException e)
{
return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
}
return Response.noContent().build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, TicketPriceDTO dto)
{
TypedQuery<TicketPrice> findByIdQuery = em.createQuery("SELECT DISTINCT t FROM TicketPrice t LEFT JOIN FETCH t.show LEFT JOIN FETCH t.section LEFT JOIN FETCH t.ticketCategory WHERE t.id = :entityId ORDER BY t.id", TicketPrice.class);
findByIdQuery.setParameter("entityId", id);
TicketPrice entity;
try
{
entity = findByIdQuery.getSingleResult();
}
catch (NoResultException nre)
{
entity = null;
}
entity = dto.fromDTO(entity, em);
try
{
entity = em.merge(entity);
}
catch (OptimisticLockException e)
{
return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
}
return Response.noContent().build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, TicketDTO dto)
{
TypedQuery<Ticket> findByIdQuery = em.createQuery("SELECT DISTINCT t FROM Ticket t LEFT JOIN FETCH t.ticketCategory WHERE t.id = :entityId ORDER BY t.id", Ticket.class);
findByIdQuery.setParameter("entityId", id);
Ticket entity;
try
{
entity = findByIdQuery.getSingleResult();
}
catch (NoResultException nre)
{
entity = null;
}
entity = dto.fromDTO(entity, em);
try
{
entity = em.merge(entity);
}
catch (OptimisticLockException e)
{
return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
}
return Response.noContent().build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, EventDTO dto)
{
TypedQuery<Event> findByIdQuery = em.createQuery("SELECT DISTINCT e FROM Event e LEFT JOIN FETCH e.mediaItem LEFT JOIN FETCH e.category WHERE e.id = :entityId ORDER BY e.id", Event.class);
findByIdQuery.setParameter("entityId", id);
Event entity;
try
{
entity = findByIdQuery.getSingleResult();
}
catch (NoResultException nre)
{
entity = null;
}
entity = dto.fromDTO(entity, em);
try
{
entity = em.merge(entity);
}
catch (OptimisticLockException e)
{
return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
}
return Response.noContent().build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, MediaItemDTO dto)
{
TypedQuery<MediaItem> findByIdQuery = em.createQuery("SELECT DISTINCT m FROM MediaItem m WHERE m.id = :entityId ORDER BY m.id", MediaItem.class);
findByIdQuery.setParameter("entityId", id);
MediaItem entity;
try
{
entity = findByIdQuery.getSingleResult();
}
catch (NoResultException nre)
{
entity = null;
}
entity = dto.fromDTO(entity, em);
try
{
entity = em.merge(entity);
}
catch (OptimisticLockException e)
{
return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
}
return Response.noContent().build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, SectionAllocationDTO dto)
{
TypedQuery<SectionAllocation> findByIdQuery = em.createQuery("SELECT DISTINCT s FROM SectionAllocation s LEFT JOIN FETCH s.performance LEFT JOIN FETCH s.section WHERE s.id = :entityId ORDER BY s.id", SectionAllocation.class);
findByIdQuery.setParameter("entityId", id);
SectionAllocation entity;
try
{
entity = findByIdQuery.getSingleResult();
}
catch (NoResultException nre)
{
entity = null;
}
entity = dto.fromDTO(entity, em);
try
{
entity = em.merge(entity);
}
catch (OptimisticLockException e)
{
return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
}
return Response.noContent().build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, SectionDTO dto)
{
TypedQuery<Section> findByIdQuery = em.createQuery("SELECT DISTINCT s FROM Section s LEFT JOIN FETCH s.venue WHERE s.id = :entityId ORDER BY s.id", Section.class);
findByIdQuery.setParameter("entityId", id);
Section entity;
try
{
entity = findByIdQuery.getSingleResult();
}
catch (NoResultException nre)
{
entity = null;
}
entity = dto.fromDTO(entity, em);
try
{
entity = em.merge(entity);
}
catch (OptimisticLockException e)
{
return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
}
return Response.noContent().build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, VenueDTO dto)
{
TypedQuery<Venue> findByIdQuery = em.createQuery("SELECT DISTINCT v FROM Venue v LEFT JOIN FETCH v.sections LEFT JOIN FETCH v.mediaItem WHERE v.id = :entityId ORDER BY v.id", Venue.class);
findByIdQuery.setParameter("entityId", id);
Venue entity;
try
{
entity = findByIdQuery.getSingleResult();
}
catch (NoResultException nre)
{
entity = null;
}
entity = dto.fromDTO(entity, em);
try
{
entity = em.merge(entity);
}
catch (OptimisticLockException e)
{
return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
}
return Response.noContent().build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, ShowDTO dto)
{
TypedQuery<Show> findByIdQuery = em.createQuery("SELECT DISTINCT s FROM Show s LEFT JOIN FETCH s.event LEFT JOIN FETCH s.venue LEFT JOIN FETCH s.performances LEFT JOIN FETCH s.ticketPrices WHERE s.id = :entityId ORDER BY s.id", Show.class);
findByIdQuery.setParameter("entityId", id);
Show entity;
try
{
entity = findByIdQuery.getSingleResult();
}
catch (NoResultException nre)
{
entity = null;
}
entity = dto.fromDTO(entity, em);
try
{
entity = em.merge(entity);
}
catch (OptimisticLockException e)
{
return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
}
return Response.noContent().build();
}
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, BookingDTO dto)
{
TypedQuery<Booking> findByIdQuery = em.createQuery("SELECT DISTINCT b FROM Booking b LEFT JOIN FETCH b.tickets LEFT JOIN FETCH b.performance WHERE b.id = :entityId ORDER BY b.id", Booking.class);
findByIdQuery.setParameter("entityId", id);
Booking entity;
try
{
entity = findByIdQuery.getSingleResult();
}
catch (NoResultException nre)
{
entity = null;
}
entity = dto.fromDTO(entity, em);
try
{
entity = em.merge(entity);
}
catch (OptimisticLockException e)
{
return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
}
return Response.noContent().build();
}
@Override
@Retry(times = 10, on = OptimisticLockException.class)
public Product updateName(final Long id, final String name) {
return transactionTemplate.execute(new TransactionCallback<Product>() {
@Override
public Product doInTransaction(TransactionStatus status) {
Product product = entityManager.find(Product.class, id);
product.setName(name);
LOGGER.info("Updating product {} name to {}", product, name);
product = entityManager.merge(product);
entityManager.flush();
return product;
}
});
}