當前位置: 首頁>>代碼示例>>Java>>正文


Java OptimisticLockException類代碼示例

本文整理匯總了Java中javax.persistence.OptimisticLockException的典型用法代碼示例。如果您正苦於以下問題:Java OptimisticLockException類的具體用法?Java OptimisticLockException怎麽用?Java OptimisticLockException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


OptimisticLockException類屬於javax.persistence包,在下文中一共展示了OptimisticLockException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: globalsettingsHolidaysYearPost

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
@Override
@PreAuthorize("hasAuthority('admin')")
public ResponseEntity<Object> globalsettingsHolidaysYearPost( @Min(2000) @Max(2100)@ApiParam(value = "",required=true ) @PathVariable("year") Integer year,
    @ApiParam(value = "The holidays to set" ,required=true )  @Valid @RequestBody Holidays holidays)  throws ApiException {
    try {
         
    globalsettingsService.setHolidays(year, holidays);
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    
    } catch (OptimisticLockException ex) {
        try {
            Holidays lastHolidays = globalsettingsService.getHolidays(year);
            throw new ConcurrentModificationException(409, "Concurrent modification error.", lastHolidays);
        } catch (ApiException ex1) {
            Logger.getLogger(SettingsApiController.class.getName()).log(Level.SEVERE, null, ex1);
            throw new ApiException(500, "Concurrent modification exception: internal error");
        }
    }    
    
}
 
開發者ID:jrtechnologies,項目名稱:yum,代碼行數:21,代碼來源:GlobalsettingsApiController.java

示例2: update

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, Person entity) {
	if (entity == null) {
		return Response.status(Status.BAD_REQUEST).build();
	}
	if (id == null) {
		return Response.status(Status.BAD_REQUEST).build();
	}
	if (!id.equals(entity.getId())) {
		return Response.status(Status.CONFLICT).entity(entity).build();
	}
	if (em.find(Person.class, id) == null) {
		return Response.status(Status.NOT_FOUND).build();
	}
	try {
		entity = em.merge(entity);
	} catch (OptimisticLockException e) {
		return Response.status(Response.Status.CONFLICT)
				.entity(e.getEntity()).build();
	}

	return Response.noContent().build();
}
 
開發者ID:gastaldi,項目名稱:demo-ang2,代碼行數:26,代碼來源:PersonEndpoint.java

示例3: test_RollbackExceptionHandling_rollbackafterthrown

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
@Test
public void test_RollbackExceptionHandling_rollbackafterthrown()
        throws Exception {
    TransactionManager tm = mockTm();
    when(tm.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, Status.STATUS_MARKED_ROLLBACK);
    doThrow(new RollbackException().initCause(new OptimisticLockException())).when(tm).commit();
    XAJpaTemplate tx = new XAJpaTemplate(emSupplier, tm, coordinator);
    try {
        tx.tx(TransactionType.Required, new EmConsumer() {
            public void accept(EntityManager em) {
                em.persist(new Object());
            }
        });
    } catch (RuntimeException e) {
        // this is ok
    }
    verify(tm, times(5)).getStatus();
    verify(tm, times(1)).commit();
    verify(tm, times(1)).rollback();
}
 
開發者ID:apache,項目名稱:aries-jpa,代碼行數:21,代碼來源:XAJpaTemplateTest.java

示例4: settingsPut

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
@Override
@PreAuthorize("hasAuthority('hungry')")
@Transactional
public ResponseEntity<Object> settingsPut(@ApiParam(value = "User data" ,required=true ) @RequestBody Settings upUser, Errors errors) throws ApiException{
    
    if (errors.hasErrors()) 
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    
    try {
        settingsService.settingsPut(upUser);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } catch (OptimisticLockException ex) {
        try {
            User user = settingsService.settingsGet();
            throw new ConcurrentModificationException(409, "Concurrent modification error.", user);
        } catch (ApiException ex1) {
            Logger.getLogger(SettingsApiController.class.getName()).log(Level.SEVERE, null, ex1);
            throw new ApiException(500, "Concurrent modification exception: internal error");
        }
    }  

}
 
開發者ID:jrtechnologies,項目名稱:yum,代碼行數:23,代碼來源:SettingsApiController.java

示例5: globalsettingsPut

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
@Override
@PreAuthorize("hasAuthority('admin')")
@Transactional
public ResponseEntity<Object> globalsettingsPut(@ApiParam(value = "The global settings to be updated" ,required=true ) @RequestBody GlobalSettings settings) throws ApiException{
    
    try {
        globalsettingsService.globalsettingsPut(settings);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } catch (OptimisticLockException ex) {
        try {
            GlobalSettings globalSettings = globalsettingsService.globalsettingsGet();
            throw new ConcurrentModificationException(409, "Concurrent modification error.", globalSettings);
        } catch (ApiException ex1) {
            Logger.getLogger(SettingsApiController.class.getName()).log(Level.SEVERE, null, ex1);
            throw new ApiException(500, "Concurrent modification exception: internal error");
        }
    }

}
 
開發者ID:jrtechnologies,項目名稱:yum,代碼行數:20,代碼來源:GlobalsettingsApiController.java

示例6: dailyMenusIdPut

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
/**
 * @update. Chef updates the daily menu
 */
@Override
@PreAuthorize("hasAuthority('chef')")
@Transactional
public ResponseEntity<Object> dailyMenusIdPut(@ApiParam(value = "",required=true ) @PathVariable("id") String id,
    @ApiParam(value = "The daily menu to be updated" ,required=true ) @RequestBody DailyMenuEdit dailyMenu) throws ApiException, ConcurrentModificationException, ConcurrentDeletionException {
    
    Long dailyMenusId = Long.parseLong(id); // id (DTO) from the getDailyMenuChef he wants to insert foods
    
    try {
        //dailyMenuService.dailyMenusIdPut(dailyMenusId, dailyMenu);
        /****         HttpStatus.OK        ****/
        return new ResponseEntity<>( dailyMenuService.dailyMenusIdPut(dailyMenusId, dailyMenu), HttpStatus.OK);
        /****         HttpStatus.OK        ****/
    } catch (OptimisticLockException ex) {
        Logger.getLogger(DailyMenusApiController.class.getName()).log(Level.SEVERE, null, ex);
        throw new ApiException(500, "Concurrent modification exception: internal error");
    }     
}
 
開發者ID:jrtechnologies,項目名稱:yum,代碼行數:22,代碼來源:DailyMenusApiController.java

示例7: usersIdPut

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
@Override
@PreAuthorize("hasAuthority('admin')")
public ResponseEntity<Object> usersIdPut(@ApiParam(value = "", required = true) @PathVariable("id") Long id,
        @ApiParam(value = "The user data to be updated", required = true) @Valid @RequestBody UserSettings user, Errors errors) throws ApiException, Exception {
    if (errors.hasErrors()) {//Check for validation error from UserSettings class(package:model)
        Error error = new Error();
        error.setError("400");
        error.setMessage("Validation Failed");
        System.out.println("" + errors.getAllErrors());
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }
    try {
        //Call method for update user from class UsersService.
        userService.usersIdPut(user, id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } catch (OptimisticLockException ex) {
        try {
            User newUserVersion = userService.userIdGet(id);
            throw new ConcurrentModificationException(409, "Concurrent modification error", newUserVersion);    
        } catch (ApiException ex1){
            Logger.getLogger(UsersApiController.class.getName()).log(Level.SEVERE, null, ex1);
            throw new ApiException(500, "Concurrent modification exception: internal error");
        }
    }
}
 
開發者ID:jrtechnologies,項目名稱:yum,代碼行數:26,代碼來源:UsersApiController.java

示例8: updateAfnemerindicatieBlob

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
@Override
public void updateAfnemerindicatieBlob(final long persoonId, final Long lockVersiePersoon, final Long afnemerindicatieLockVersie) throws BlobException {
    final List<PersoonAfnemerindicatie> afnemerindicatiesNaToevoegen = afnemerindicatieRepository.haalAfnemerindicatiesOp(persoonId);
    final AfnemerindicatiesBlob afnemerindicatiesBlob = Blobber.maakBlob(afnemerindicatiesNaToevoegen);
    LOGGER.info("Blobify persoon:{}", persoonId);
    final byte[] afnemerindicatiesBlobBytes = Blobber.toJsonBytes(afnemerindicatiesBlob);
    //lockversieafnemerindicatiege = null uit initiele vulling of nog geen afnemerindicatie aanwezig
    final String sql
            = "UPDATE kern.perscache pc "
            + "SET lockversieafnemerindicatiege = CASE WHEN lockversieafnemerindicatiege IS NOT NULL THEN lockversieafnemerindicatiege + 1 ELSE  1 END, "
            + "afnemerindicatiegegevens = :afnemerindicatiegegevens "
            + "WHERE (pc.lockversieafnemerindicatiege = :lockversieAfnemerindicatie OR pc.lockversieafnemerindicatiege is null) "
            + "AND pc.pers = :persoonId "
            + "AND EXISTS "
            + "(SELECT 1 FROM kern.pers p WHERE p.id = pc.pers AND p.lockversie = :persoonLock )";
    final NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(masterDataSource);
    final Map<String, Object> parameters = new HashMap<>();
    parameters.put("afnemerindicatiegegevens", afnemerindicatiesBlobBytes);
    parameters.put("lockversieAfnemerindicatie", afnemerindicatieLockVersie);
    parameters.put("persoonId", persoonId);
    parameters.put("persoonLock", lockVersiePersoon);
    final int rowsUpdated = jdbcTemplate.update(sql, parameters);
    if (rowsUpdated != 1) {
        throw new OptimisticLockException("PersoonCache is ondertussen gewijzigd.");
    }
}
 
開發者ID:MinBZK,項目名稱:OperatieBRP,代碼行數:27,代碼來源:PersoonCacheJpaRepositoryImpl.java

示例9: verwijderAfnemerindicatie

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
@Override
public void verwijderAfnemerindicatie(final long persoonId, final short partijId, final int leveringsautorisatieId, final int dienstIdVerval) {
    final PersoonAfnemerindicatie persoonAfnemerindicatieVoorOpslag = zoekAfnemerindicatie(persoonId, partijId, leveringsautorisatieId);
    if (persoonAfnemerindicatieVoorOpslag == null || !persoonAfnemerindicatieVoorOpslag.isActueelEnGeldig()) {
        final String foutMelding = String.format("Het verwijderen van de afnemerindicatie is mislukt, er is geen afnemerindicatie"
                        + " aangetroffen met deze gegevens: persoonId %d, leveringsautorisatieId %s, partijCode %d", persoonId,
                leveringsautorisatieId, partijId);
        throw new OptimisticLockException(foutMelding);
    }
    persoonAfnemerindicatieVoorOpslag.setActueelEnGeldig(false);
    //zoek his record dat moet vervallen.
    PersoonAfnemerindicatieHistorie his = null;
    for (PersoonAfnemerindicatieHistorie persoonAfnemerindicatieHistorie : persoonAfnemerindicatieVoorOpslag.getPersoonAfnemerindicatieHistorieSet()) {
        if (!persoonAfnemerindicatieHistorie.isVervallen()) {
            his = persoonAfnemerindicatieHistorie;
            his.setDienstVerval(entityManager.getReference(Dienst.class, dienstIdVerval));
            his.setDatumTijdVerval(new Timestamp(System.currentTimeMillis()));
            break;
        }
    }
    Assert.notNull(his, "Niet vervallen Afnemerindicatie hisrecord niet gevonden");
    entityManager.persist(persoonAfnemerindicatieVoorOpslag);
}
 
開發者ID:MinBZK,項目名稱:OperatieBRP,代碼行數:24,代碼來源:AfnemerindicatieJpaRepositoryImpl.java

示例10: onServerError

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
@Override
public CompletionStage<Result> onServerError(Http.RequestHeader request, Throwable exception) {
    return CompletableFuture.supplyAsync(() -> {
        Throwable cause = exception.getCause();
        String errorMessage = cause == null ? exception.getMessage() : cause.getMessage();
        Logger.error("onServerError: URL: {}, msg: {}", request.uri(), errorMessage);
        exception.printStackTrace();
        if (cause != null) {
            if (cause instanceof MalformedDataException) {
                return Results.badRequest(Json.toJson(errorMessage));
            }
            if (cause instanceof IllegalArgumentException) {
                return Results.badRequest(Json.toJson(new ApiError(errorMessage)));
            }
            if (cause instanceof OptimisticLockException) {
                return Results.badRequest("sitnet_error_data_has_changed");
            }
        }
        return Results.internalServerError(Json.toJson(new ApiError(errorMessage)));
    });
}
 
開發者ID:CSCfi,項目名稱:exam,代碼行數:22,代碼來源:SystemErrorHandler.java

示例11: resetSequence

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
public void resetSequence(String seqName) {
       int tries = 0;
       final int maxTries = 100;
       do {
           try {
               sequenceEngine.resetSequenceInNewTransaction(seqName);
               break;
           } catch (EJBException e) {
               if (e.getCausedByException() instanceof OptimisticLockException) {
               	log.warn("OptimisticLockException occured (" + tries + "). try again...");
                   tries++;
               } else {
               	log.error("EJBException occured. ", e);
                   throw e;
               }
           }
       } while (tries < maxTries);

       if (tries >= maxTries) {
       	log.error("Cannot get Sequence. Give it up after " + maxTries + " tries");
           final String msg = "Cannot get Sequence. Exceeded maxTries=" + maxTries + " attempts";
           throw new EJBException(msg);
       }
}
 
開發者ID:salimvanak,項目名稱:myWMS,代碼行數:25,代碼來源:LOSSequenceGeneratorServiceBean.java

示例12: optimisticLockingWorks

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
@Test(expected=OptimisticLockException.class)
@Transactional
public void optimisticLockingWorks() {
	Employee employeeInVacation = entityManager.find(Employee.class, employeeId);
	entityManager.detach(employeeInVacation); // sent to Tahiti
	
	employeeInVacation.setName("new Name");
	
	// meanwhile, another client changes the same entity
	txUtil.executeInSeparateTransaction(() -> {
		Employee employee2 = entityManager.find(Employee.class, employeeId);
		System.out.println("Before 1st change: @Version in DB = " + employee2.getVersion());
		employee2.setName("concurrent name");
	});
	
	System.out.println("Before 2nd change");
	System.out.println("@Version in DB = " + entityManager.find(Employee.class, employeeId).getVersion());
	System.out.println("@Version in incoming data = " + employeeInVacation.getVersion());
	
	entityManager.merge(employeeInVacation); // try to re-attach
}
 
開發者ID:victorrentea,項目名稱:training,代碼行數:22,代碼來源:MasterPlay.java

示例13: store

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
public Prediction store(Prediction prediction) throws GameLockedException {
    final GameLockedException gameLockedException = new GameLockedException(
            "The game " + prediction.getForGame().getHomeTeam() + " - " +
                    prediction.getForGame().getAwayTeam() + " was locked before you submitted your proposal.");
    try {
        if (entityManager.merge(prediction.getForGame()).isLocked()) {
            throw gameLockedException;
        }
    } catch (OptimisticLockException ole) {
        throw gameLockedException;
    }

    if (prediction.getId() == null) {
        Game mergedGame = entityManager.merge(prediction.getForGame());
        mergedGame.getPredictions().add(prediction);
        prediction.setForGame(mergedGame);

        User mergedUser = entityManager.merge(prediction.getByUser());
        mergedUser.getPredictions().add(prediction);
        prediction.setByUser(mergedUser);
        return prediction;
    } else {
        return entityManager.merge(prediction);
    }
}
 
開發者ID:ivannov,項目名稱:predcomposer,代碼行數:26,代碼來源:PredictionsService.java

示例14: delete

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
@Authentication({User.Role.ADMIN})
public static Result delete(long i) {
    Drone drone = Drone.FIND.byId(i);
    if (drone == null) {
        return notFound();
    }
    boolean updated = false;
    while (!updated) {
        drone.refresh();
        if (drone.getStatus() == Drone.Status.FLYING) {
            return forbidden("Cannot remove drone while flying.");
        }
        try {
            drone.delete();
            updated = true;
        } catch (OptimisticLockException ex) {
            updated = false;
        }
    }
    Fleet.getFleet().stopCommander(drone);
    return ok(ControllerHelper.EMPTY_RESULT);
}
 
開發者ID:ugent-cros,項目名稱:cros-core,代碼行數:23,代碼來源:DroneController.java

示例15: saveLifecycle

import javax.persistence.OptimisticLockException; //導入依賴的package包/類
@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);
}
 
開發者ID:zalando-stups,項目名稱:fullstop,代碼行數:33,代碼來源:ApplicationLifecycleServiceImpl.java


注:本文中的javax.persistence.OptimisticLockException類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。