From: Kai Moritz Date: Sun, 25 Oct 2020 14:24:39 +0000 (+0100) Subject: Wiredly enforcing uniqe-users with an exception X-Git-Tag: part-1~7 X-Git-Url: http://juplo.de/gitweb/?a=commitdiff_plain;h=4e3b5cd357003eb6235b14e65cfbf1fca3424c17;p=demos%2Fspring%2Fdata-jdbc Wiredly enforcing uniqe-users with an exception --- diff --git a/src/main/java/de/juplo/boot/data/jdbc/User.java b/src/main/java/de/juplo/boot/data/jdbc/User.java index 16587c1..2cc62bd 100644 --- a/src/main/java/de/juplo/boot/data/jdbc/User.java +++ b/src/main/java/de/juplo/boot/data/jdbc/User.java @@ -25,4 +25,10 @@ public class User { this.created = created; this.loggedIn = loggedIn; } + + + @Override + public String toString() { + return username; + } } 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 177b120..ac5ddbc 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.*; @@ -46,6 +47,9 @@ public class UserController { @RequestBody String username) { String sanitizedUsername = UserController.sanitize(username); User user = new User(sanitizedUsername, LocalDateTime.now(), false); + + LOG.info("Request to create user: {}", user); + repository.save(user); publisher.publishEvent( new UserEvent( @@ -53,6 +57,10 @@ public class UserController { sanitizedUsername, CREATED, ZonedDateTime.now(clock))); + + // Triggers an IncorrectResultSizeDataAccessException, if the user already existed! + user = repository.findByUsername(sanitizedUsername); + UriComponents uri = builder .fromCurrentRequest() @@ -101,4 +109,13 @@ public class UserController { return string.trim().toLowerCase(); } + + @ExceptionHandler + public ResponseEntity incorrectResultSizeDataAccessException( + IncorrectResultSizeDataAccessException e + ) + { + LOG.info("User already exists!"); + return ResponseEntity.badRequest().build(); + } }