From: Kai Moritz Date: Sun, 12 Jul 2020 13:00:39 +0000 (+0200) Subject: Wiredly enforcing uniqe-users with an exception X-Git-Url: http://juplo.de/gitweb/?a=commitdiff_plain;h=9a913cd7691592c38257a705123a8d16677be2cb;p=demos%2Fspring%2Fdata-jdbc Wiredly enforcing uniqe-users with an exception --- diff --git a/src/main/java/de/juplo/boot/data/jdbc/UserController.java b/src/main/java/de/juplo/boot/data/jdbc/UserController.java index 3087290..0aaefd5 100644 --- a/src/main/java/de/juplo/boot/data/jdbc/UserController.java +++ b/src/main/java/de/juplo/boot/data/jdbc/UserController.java @@ -3,6 +3,7 @@ package de.juplo.boot.data.jdbc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; +import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; @@ -41,8 +42,12 @@ public class UserController { @RequestBody String username) { String sanitizedUsername = UserController.sanitize(username); User user = new User(sanitizedUsername, LocalDateTime.now(), false); + + // Triggering a unique-error for username prevents persistence repository.save(user); publisher.publishEvent(new UserEvent(this, CREATED, sanitizedUsername)); + user = repository.findByUsername(sanitizedUsername); + UriComponents uri = builder .fromCurrentRequest() @@ -86,4 +91,13 @@ public class UserController { return string.trim().toLowerCase(); } + + @ExceptionHandler + public ResponseEntity incorrectResultSizeDataAccessException( + IncorrectResultSizeDataAccessException e + ) + { + LOG.info("User already exists!"); + return ResponseEntity.badRequest().build(); + } }