From 956bdad01d854474a27b8542b90f665db6db76e7 Mon Sep 17 00:00:00 2001 From: Pekka Helenius Date: Fri, 18 Sep 2020 12:41:54 +0300 Subject: [PATCH] Error if attempting to add a non-unique ISBN value Signed-off-by: Pekka Helenius --- .../src/main/java/com/fjordtek/bookstore/model/Book.java | 4 +--- .../java/com/fjordtek/bookstore/web/BookController.java | 7 +++++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/bookstore/src/main/java/com/fjordtek/bookstore/model/Book.java b/bookstore/src/main/java/com/fjordtek/bookstore/model/Book.java index 1a5595c..43c58f6 100644 --- a/bookstore/src/main/java/com/fjordtek/bookstore/model/Book.java +++ b/bookstore/src/main/java/com/fjordtek/bookstore/model/Book.java @@ -120,9 +120,7 @@ public class Book { private int year; ////////// - @Column( - unique = true - ) + @Column(unique = true) @NotBlank( message = "Fill the ISBN code form" ) diff --git a/bookstore/src/main/java/com/fjordtek/bookstore/web/BookController.java b/bookstore/src/main/java/com/fjordtek/bookstore/web/BookController.java index bb4e893..8fc9d7c 100644 --- a/bookstore/src/main/java/com/fjordtek/bookstore/web/BookController.java +++ b/bookstore/src/main/java/com/fjordtek/bookstore/web/BookController.java @@ -118,13 +118,16 @@ public class BookController { HttpServletRequest requestData ) { + // TODO consider better solution. Add custom Hibernate annotation for Book class? + if (bookRepository.existsByIsbn(book.getIsbn())) { + bindingResult.rejectValue("isbn", "error.user", "ISBN code already exists"); + } + if (bindingResult.hasErrors()) { httpServerLogger.commonError("Book add: error " + book.toString(), requestData); return bookAddPageView; } - bookRepository.save(book); - httpServerLogger.logMessageNormal( requestData, bookAddPageView + ": " + "HTTPOK"