Springboot from beginning III

Lahiru Sampath Abegunawardena
4 min readApr 29, 2020

Hi I’m lahiru Abegunawardena. This is the 3rd article on Java Springboot. In my 1st and 2nd articles on this series we discussed about storing data into mysql and retrieve all data from that table.

First of all I need to tell you that I changed responses from Store and getAll endpoints and added tryCatch blocks to prevent application from breaking when a exception occured. Following changes are applied in BookService class.

public Object storeBooks(BookModel newBook){
Map<String, Object> responseData = new HashMap<>();
try {
BookModel newBookDta = bookRepository.save(newBook);
responseData.put("msg", "New Book stored successfully..");
responseData.put("status", true);
responseData.put("data", newBookDta);
return responseData;
} catch (Exception e){
responseData.clear();
responseData.put("msg", "New Book store failed..");
responseData.put("status", false);
responseData.put("data", null);
return responseData;
}
}

public Object getAllBooks(){
Map<String, Object> responseData = new HashMap<>();
try {
Iterable<BookModel> allBooks = bookRepository.findAll();
responseData.put("msg", "All books retrieved..");
responseData.put("status", true);
responseData.put("data", allBooks);
return responseData;
} catch (Exception e){
responseData.put("msg", "All books retrieve failed..");
responseData.put("status", false);
responseData.put("data", null);
return responseData;
}
}

Also I had to change return types of those functions in BookControler to Object to accept responses returned from this changed Service class functions. I have returned response as json with data, status and message with using Map in Java. Let’s see how this changed format of the response.

@PostMapping("/store")
public Object storeBooks(@RequestBody BookModel newBook){
return bookService.storeBooks(newBook);
}

@GetMapping("")
public Object getAllBooks(){
return bookService.getAllBooks();
}

Now we will look into today discussion. First we’ll see how to retrieve data by it’s id. First I’ll show you the code in Service class.

public Object getBookById(Integer bookId){
Map<String, Object> responseData = new HashMap<>();
try {
if(bookRepository.existsById(bookId)){
Optional<BookModel> existDta = bookRepository.findById(bookId);
responseData.put("msg", "Book found by bookId");
responseData.put("status", true);
responseData.put("data", existDta);
} else {
responseData.clear();
responseData.put("msg", "There is no book exists by this id..");
responseData.put("status", false);
responseData.put("data", null);
}
return responseData;
} catch (Exception e){
responseData.clear();
responseData.put("msg", e.getMessage());
responseData.put("status", false);
responseData.put("data", null);
return responseData;
}
}

You need to add above code into service class. Optional<BookModel> is the data type of response that returns from findById() function which inherited from CrudRepository interface. I have created this function to get bookId as a parameter to get Book data by Id in “book” relation. Within this try{} block first I check if there is any book exists in passed id in url , then I return object that has true status and success message with dataset. If passed bookId doesn’t exist I return status false response with relevant message. Now we will see how we have created function in BookController to accept the GET api request.

@GetMapping("/{bookId}")
public Object getBookById(@PathVariable Integer bookId){
return bookService.getBookById(bookId);
}

You can see that I have created this function to listen to GET request on localhost:8080/books/book_id. I have passed paremeter into getBookById function to get bookId through GET url by using @PathVariable annotation. Let’s see some examples on discussed scenarios.

Find Book by Id (Non existing)
Find Book by Id (existing)

Now we will discuss about updating a data on book entity. As we discussed on the first aricle I created a function on BookController to accept PUT request on http://localhost:8080/books/update/id.

@PutMapping("/update/{bookId}")
public Object updateBook(@PathVariable Integer bookId, @RequestBody BookModel updtBkDta){
return bookService.updateBook(bookId, updtBkDta);
}

As our previous discussions you must identify usages of @PathVariable and @RequestBody annotations. I have also created updateBook function on BookService business service class.

public Object updateBook(Integer bookId, BookModel updtBkDta){
try {
Map<String, Object> responseData = new HashMap<>();

if(bookRepository.existsById(bookId)){
BookModel updatedDta = bookRepository.save(updtBkDta);
responseData.put("msg", "Book updated successfully");
responseData.put("status", true);
responseData.put("data", updatedDta);
return responseData;
} else {
responseData.put("msg", "There is no book exists by this id..");
responseData.put("status", false);
responseData.put("data", null);
return responseData;
}
} catch (Exception e){
Map<String, Object> responseData = new HashMap<>();
responseData.put("msg", e.getMessage());
responseData.put("status", false);
responseData.put("data", null);
return responseData;
}
}

I have created this function to get bookId as a parameter and details that need to be updated. Within this try{} block first I check if there is any book exists in passed id in url, then after perform update I return object that has true status and success message with updated dataset. If you passed bookId that doesn’t exist I followed same scenario I used for getById functionality. I attached few screenshots below on discussed scenarios.

PUT request Update book by bookId: 1
View updated book by calling GET books/1 url
Trying to update a book that doesn’t exist

So I hope you will find this article very helpful in learning springboot. Always remember to restart application after changing code. I’ll bring the next article on delete operations and some other functionalities. As promised on last article I have updated repo with today code. If there is anything to clarify or solve please don’t hesitate to contact me via my linkedin and fbpage.

Try all of this by yourself and if there is anything feel free to comment. Like and Share with your friends.

--

--