javax.persistence.OptimisticLockException Java Examples

The following examples show how to use javax.persistence.OptimisticLockException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OptimisticLockingIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@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();
}
 
Example #2
Source File: AdminfacesAutoConfiguration.java    From joinfaces with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: OptimisticLockingIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@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();
}
 
Example #4
Source File: SaveApplicationLifecycleRetryTest.java    From fullstop with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #5
Source File: XXGlobalStateDao.java    From ranger with Apache License 2.0 6 votes vote down vote up
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...");
			}
		}
	}
 
Example #6
Source File: OptimisticLockingIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@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();
}
 
Example #7
Source File: OptimisticLockingIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@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();
}
 
Example #8
Source File: HibernateExceptionUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@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);
    }
}
 
Example #9
Source File: HibernateExceptionUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeletingADeletedObject_thenOptimisticLockException() {
    thrown.expect(isA(OptimisticLockException.class));
    thrown.expectMessage(
        "Batch update returned unexpected row count from update");
    thrown.expectCause(isA(StaleStateException.class));

    Session session = null;
    Transaction transaction = null;

    try {
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();

        Product product1 = new Product();
        product1.setId(12);
        product1.setName("Product 12");
        session.save(product1);
        transaction.commit();
        session.close();

        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
        Product product2 = session.get(Product.class, 12);
        session.createNativeQuery("delete from Product where id=12")
            .executeUpdate();
        // We need to refresh to fix the error.
        // session.refresh(product2);
        session.delete(product2);
        transaction.commit();
    } catch (Exception e) {
        rollbackTransactionQuietly(transaction);
        throw (e);
    } finally {
        closeSessionQuietly(session);
    }
}
 
Example #10
Source File: RouteHeaderServiceImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
public DocumentRouteHeaderValue saveRouteHeader(DocumentRouteHeaderValue routeHeader) {
    if ( LOG.isDebugEnabled() ) {
        LOG.debug( "About to Save the route Header: " + routeHeader.getDocumentId() + " / version="
                + routeHeader.getVersionNumber() );
        DocumentRouteHeaderValue currHeader = getDataObjectService().find(DocumentRouteHeaderValue.class,
                routeHeader.getDocumentId());
        if ( currHeader != null ) {
            LOG.debug( "Current Header Version: " + currHeader.getVersionNumber() );
        } else {
            LOG.debug( "Current Header: null" );
        }
        LOG.debug( ExceptionUtils.getStackTrace(new Throwable()) );
    }
    try {
        // before saving, copy off the document content, since it's transient it will get erased during a JPA merge
        DocumentRouteHeaderValueContent content = routeHeader.getDocumentContent();
        DocumentRouteHeaderValue drvPersisted = dataObjectService.save(routeHeader, PersistenceOption.FLUSH);
        // now let's save the content and reattach it to our document
        content.setDocumentId(drvPersisted.getDocumentId());
        content = dataObjectService.save(content);
        drvPersisted.setDocumentContent(content);
        return drvPersisted;
    } catch ( RuntimeException ex ) {
        if ( ex.getCause() instanceof OptimisticLockException) {
            LOG.error( "Optimistic Locking Exception saving document header or content. Offending object: "
                    + ex.getCause()
                    + "; DocumentId = " + routeHeader.getDocumentId() + " ;  Version Number = "
                    + routeHeader.getVersionNumber());
        }
        LOG.error( "Unable to save document header or content. Route Header: " + routeHeader, ex );
        throw ex;
    }
}
 
Example #11
Source File: Model.java    From canal with Apache License 2.0 5 votes vote down vote up
public void saveOrUpdate() {
    try {
        EbeanServer ebeanServer = Ebean.getDefaultServer();
        Object id = ebeanServer.getBeanId(this);
        if (id == null) {
            init();
            this.save();
        } else {
            this.update();
        }
    } catch (Exception e) {
        throw new OptimisticLockException(e);
    }
}
 
Example #12
Source File: HawkBitEclipseLinkJpaDialectTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
@Test
@Description("Use Case: PersistenceException that can be mapped by EclipseLinkJpaDialect into corresponding DataAccessException.")
public void jpaOptimisticLockExceptionIsConcurrencyFailureException() {
    assertThat(
            hawkBitEclipseLinkJpaDialectUnderTest.translateExceptionIfPossible(mock(OptimisticLockException.class)))
                    .isInstanceOf(ConcurrencyFailureException.class);
}
 
Example #13
Source File: HerdErrorInformationExceptionHandler.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Handle exceptions that result in a "conflict" status.
 */
@ExceptionHandler(value = {AlreadyExistsException.class, ObjectAlreadyExistsException.class, OptimisticLockException.class})
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public ErrorInformation handleConflictException(Exception exception)
{
    return getErrorInformation(HttpStatus.CONFLICT, exception);
}
 
Example #14
Source File: OptimisticLockingTest.java    From vladmihalcea.wordpress.com with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetryRunsOnTransaction() {
    assertEquals(0, itemService.getRegisteredCalls());
    try {
        itemService.saveItems();
    } catch (OptimisticLockException expected) {
    }
    assertEquals(3, itemService.getRegisteredCalls());
}
 
Example #15
Source File: ApplicationLifecycleServiceImpl.java    From fullstop with Apache License 2.0 5 votes vote down vote up
@Override
@Retryable(maxAttempts = 10, backoff = @Backoff(delay = 100, maxDelay = 500),
        include = {ObjectOptimisticLockingFailureException.class, OptimisticLockException.class, DataIntegrityViolationException.class})
@Transactional(REQUIRES_NEW)
public LifecycleEntity saveLifecycle(final ApplicationEntity applicationEntity, final VersionEntity versionEntity,
        final LifecycleEntity lifecycleToSave) {
    Assert.notNull(applicationEntity, "applicationEntity must not be null");
    Assert.notNull(versionEntity, "versionEntity must not be null");
    Assert.notNull(lifecycleToSave, "lifecycleToSave must not be null");

    ApplicationEntity applicationByName = applicationRepository.findByName(applicationEntity.getName());
    VersionEntity versionByName = versionRepository.findByName(versionEntity.getName());

    if (applicationByName == null) {
        applicationByName = applicationRepository.save(applicationEntity);
    }

    if (versionByName == null) {
        versionByName = versionRepository.save(versionEntity);
    }

    if (!applicationByName.getVersionEntities().contains(versionByName)) {
        applicationByName.getVersionEntities().add(versionByName);
        applicationByName = applicationRepository.save(applicationByName);
    }


    lifecycleToSave.setApplicationEntity(applicationByName);
    lifecycleToSave.setVersionEntity(versionByName);

    return lifecycleRepository.save(lifecycleToSave);
}
 
Example #16
Source File: ShowEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #17
Source File: ExceptionMapperTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void mapEJBExceptions_validateCause() throws Exception {
    EJBException e = new EJBException(new OptimisticLockException());
    Exception mappedException = mapper.mapToBesException(e);
    assertTrue(mappedException instanceof ConcurrentModificationException);
    assertEquals(null, mappedException.getCause());
}
 
Example #18
Source File: VenueEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #19
Source File: SectionEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #20
Source File: SectionAllocationEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #21
Source File: MediaItemEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #22
Source File: ItemServiceImpl.java    From vladmihalcea.wordpress.com with Apache License 2.0 5 votes vote down vote up
@Override
@Retry(times = 2, on = OptimisticLockException.class, failInTransaction = false)
@Transactional
public void saveItems() {
    incrementCalls();
    LOGGER.info("Save Items!");
    throw new OptimisticLockException("Save Items!");
}
 
Example #23
Source File: TicketEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #24
Source File: TicketPriceEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #25
Source File: EventCategoryEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #26
Source File: TicketCategoryEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #27
Source File: PerformanceEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #28
Source File: BookingEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #29
Source File: VenueEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #30
Source File: ShowEndpoint.java    From monolith with Apache License 2.0 5 votes vote down vote up
@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();
}