Код: Выделить всё
@Slf4j
@Service
@RequiredArgsConstructor
public class NextIdService {
private final NextIdRepository nextIdRepository;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public int getNextId(int id) {
try {
NextId nextId = nextIdRepository.findById(id).orElse(null);
if (nextid != null) {
nextId.setNext(nextId.getNext() + 1);
nextIdRepository.saveAndFlush(nextId);
return nextId.getNext();
} else {
log.debug("No record found for id...");
return -1;
}
} catch (PessimisticLockingFailureException e) {
// nextid record is locked
log.warn("Next id record is locked...");
return -1;
}
}
}
@Service
@RequiredArgsConstructor
public class ItemService {
private final ItemRepository ItemRepository;
private final NextIdService nextIdService;
public record ItemDto(Integer id, LocalDate date, LocalTime time, String message, String terminal) {
}
@Transactional
public ItemDto create(String message, String terminal) {
int nextId = nextId = nextIdService.getNextId(13);
if (nextId == -1) throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR,
"Unable to get next id!");
Item item = new item();
item.setMessage(message);
item.setTerminal(terminal + "_" + StringUtils.leftPad(String.valueOf(nextId), 4, "0"));
item.setDate(LocalDate.now());
item.setTime(LocalTime.now());
itemRepository.saveAndFlush(item);
return new ItemDto(item.getId(), item.getDate(), item.getTime(), item.getMessage(),
item.getTerminal());
}
}
Я также попробовал использовать параметр noRollbackForClassName = Exception.class для аннотации @Transactionl метода getNextId(id) следующим образом:
Код: Выделить всё
@Transactional(propagation = Propagation.REQUIRES_NEW, noRollbackFor = Exception.class)
Мне пришлось использовать Propagation = Параметр Propagation.REQUIRES_NEW в транзакции, позволяющий немедленно освободить запись после следующего обновления идентификатора, а не ждать, пока метод create(...) ItemService полностью освободит ее.
Я ожидаю, что смогу обработать случай LOCK, не вызывая каких-либо исключений из метода getNextId(id) и возвращая -1, если значение записи не может быть обновлено.>
Подробнее здесь: https://stackoverflow.com/questions/790 ... propagates
Мобильная версия