Rest API with Spring Boot, MySQL , Hibernate, JPA — Part 3

Hi, today I’m continuing the Rest API part-2 where I implemented Model & Repository packages for the Rest API.

Pic fom Google

Here, I’m going to do the controller part & exception handling.

Create a new package called controller & inside that create a BookController.java file which contains the end points.

package com.rest.API.controller;

import com.rest.API.exception.BookNotFoundException;
import com.rest.API.model.Book;
import com.rest.API.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import javax.validation.Valid;
import java.util.List;

@RestController
public class BookController {

@Autowired
BookRepository bookRepository;

// Get All Notes
@GetMapping("/books")
public List<Book> getAllNotes() {
return bookRepository.findAll();
}

// Create a new Note
@PostMapping("/books")
public Book createNote(@Valid @RequestBody Book book) {
return bookRepository.save(book);
}

// Get a Single Note
@GetMapping("/books/{id}")
public Book getNoteById(@PathVariable(value = "id") Long bookId) throws BookNotFoundException {
return bookRepository.findById(bookId)
.orElseThrow(() -> new BookNotFoundException(bookId));
}

// Update a Note
@PutMapping("/books/{id}")
public Book updateNote(@PathVariable(value = "id") Long bookId,
@Valid @RequestBody Book bookDetails) throws BookNotFoundException {

Book book = bookRepository.findById(bookId)
.orElseThrow(() -> new BookNotFoundException(bookId));

book.setBook_name(bookDetails.getBook_name());
book.setAuthor_name(bookDetails.getAuthor_name());
book.setIsbn(bookDetails.getIsbn());

Book updatedBook = bookRepository.save(book);

return updatedBook;
}

// Delete a Note
@DeleteMapping("/books/{id}")
public ResponseEntity<?> deleteBook(@PathVariable(value = "id") Long bookId) throws BookNotFoundException {
Book book = bookRepository.findById(bookId)
.orElseThrow(() -> new BookNotFoundException(bookId));

bookRepository.delete(book);

return ResponseEntity.ok().build();
}
}

The first imported package in for the Book Not Found Exception; which we are going to create a file in a bit.

Explanation of Annotations we used here are:

  1. RestController : This annotation used to denote the every methods in the annotated class are as Domain Object.

So what is Domain Object..?

Simply says..,

Domain Object == Business Object.

They usually used to represent by entities and value objects related to the end point we are giving to get the data from database.

2. Autowired: This annotation is used to wire the bean classes automatically.

For that, you need to know about “What is bean Class..?”

I will write a separate article on Bean Class for a clear understanding. Basically Java Bean Class is a simple class which encapsulates many objects into it.

The following are the Mapping Annotations for the endpoints to perform CRUD Operations.

3. GetMapping : This is an interface which contains the path of the endpoint to perform Get method. This GetMapping interface uses RequestMapping interface which can have the “path, value, params, headers” method to perform the Get method in earlier Spring.

Now its simplified by using GetMapping

4. PostMapping : This is an interface which contains the path of the endpoint to perform Post method

5. PutMapping :This is an interface which contains the path of the endpoint to perform Put method to Update

6. DeleteMapping :This is an interface which contains the path of the endpoint to perform Delete method

In the final lines you have seen “ResponseEntity” keyword.

What is that…??

Its a Java class which inherits HttpEntity class to manipulate the HTTP Responses. Whether the request of the connection is “OK” or else if there any problem throw an exception from the HttpEntity class.

orElseThrow() : This is a method found in Optional class in Java8 which is introduced to handle Exceptions. Optional class provides various utility methods to check the presence or absence of an object, which helps to deal with NullPointerException. orElseThrow is a method — Return a value if present, otherwise invoke an exception by created by our self and throws an exception.


In that Exception I created a BookNotFoundException. So let’s have a look at the code in that exception class.

package com.rest.API.exception;

public class BookNotFoundException extends Exception {

private long book_id;

public BookNotFoundException(long book_id) {
super(String.format("Book is not found with id : '%s'", book_id));
}

}

The created class extends the Super class of Exception & in the constructor I’m passing the book_id & prints the exception .

So, that’s it…

We have finished the REST API part. Now you can build the app which was explained in Part 1 & do some Testings with Postman.


Now we have to connect to with database as MySQL.

Inside application.properties your resources folder add the following :

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url = jdbc:mysql://localhost:3306/library
spring.datasource.username
= root //normally put your MySQL username
spring.datasource.password
= YOUR_MYSQL_PASSWORD


## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

That’s it.

Happy Coding Folks…!!

My Previous Articles

  1. Rest API with Spring Boot, MySQL , Hibernate, JPA — Part 1 — Introduction Only
  2. Rest API with Spring Boot, MySQL , Hibernate, JPA — Part 2 — Implementation
  3. Split & Map a String in Java
  4. Annotation & their uses in Java
  5. Java Bean Class