本文整理汇总了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");
}
}
}
示例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();
}
示例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();
}
示例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");
}
}
}
示例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");
}
}
}
示例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");
}
}
示例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");
}
}
}
示例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.");
}
}
示例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);
}
示例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)));
});
}
示例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);
}
}
示例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
}
示例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);
}
}
示例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);
}
示例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);
}