Springboot Database Rest API

Dec 10th, 2020


Springboot logo

Springboot

Springboot is a Java framework that allows us to build web services, such as rest, at an accelerated rate. It provides an embedded Tomcat server, and builds single bootable fat jars. We will be building a simple Rest API using the Spring Data JPA.

Spring Data JPA

The Spring Data JPA is a library that allows to write easily maintainable code to interact with data-sources.

Building the Application

To initialize the project, head over to the Spring Initilizer. Be sure to select the Spring Data JPA and Lombok project dependencies.

We will be building a simple service to save and fetch books and their authors.

The Data Layer

Lets create a new package named 'data'. Now lets add a Book entity.


@Entity
@Data
public class Book{

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Long id;

  private String isbn;

  private String name;

  private String author;

}

As you can see, we have a book table, with a auto generated id column of type Long, an isbn column of type String, a name column of type String, and an author column of type String. We use the Lombok @Data annotation to automatically generate getters and setters for our Java bean.

Now lets create a Book JPA Repository named 'BookRepository'and add getAll and findByAuthor methods.


@Repository
public interface BookRepository extends JpaRepository<Book, Long> {

  @Query("SELECT b FROM Book b")
  List<Book> getAll();

  List<Book> findByAuthor(String author);

}

We can use the @Query annotation to execute a custom SQL statement. We also use the @Repository annotation to tell the Spring container that is a JpaRepository.

Now lets create a service to interact with our book table.


@Service
public class BookService {

  private final BookRepository bookRepository;

  @Autowired
  public BookService(BookRepository bookRepository){
    this.bookRepository = bookRepository;
  }

  public Book saveBook(String isbn, String name, String author){
    Book book = new Book();
    book.setIsbn(isbn);
    book.setName(name);
    book.setAuthor(author);
    return this.bookRepository.save(book);
  }

  public List<Book> getAllBooks(){
    return this.bookRepository.getAll();
  }

  public List<Book> getBooksByAuthor(String author){
    return this.bookRepository.findByAuthor(author);
  }

}

Now our BookService allows us to save new books, and fetch previously saved books. We use the @Service annotation to tell the Spring container that this is an inject-able service component.

Web Service Layer

Lets create a new package named 'rest'.

Now create a bean to represent a create book request.


@Data
public class CreateBookRequest {

  private String isbn;
  private String name;
  private String author;

}

Now we will create an interface for our rest controller component.


public interface BookController {

  public Book saveBook(SaveBookRequest saveBookRequest);

  public List<Book> getAllBooks();

  public List<Book> getBooksByAuthor(String author);

}

Now we need a concrete implementation.


@RestController
public class BookControllerImpl implements BookController {

  private final BookService bookService;

  @Autowired
  public BookControllerImpl(BookService bookService) {
    this.bookService = bookService;
  }

  @PostMapping("/books")
  public Book saveBook(CreateBookRequest createBookRequest) {
    return this.bookService.saveBook(createBookRequest.getIsbn(), 
                                     createBookRequest.getName()
                                     createBookRequest.getAuthor());
  }

  @GetMapping("/books")
  public List<Book> getBooks(
    @RequestParam(required = false, defaultValue = "", value = "author") String author
  ) {
    if(author.isEmpty()) {
      return this.bookService.getAllBooks();
    } else {
      return this.bookService.getBooksByAuthor(author);
    }
  }

}

We use the @RestController annotation to tell the Spring container that this is indeed a rest controller.

Now we have one endpoint, /books, that we can interact with. We have the POST method to create a book, and the GET method to fetch books.

Interact with the Service

Lets fire up our rest web service, and hit it with our favorite Rest tool, like Postman.

To start the service, run the bootRun build command.

Lets create a book:


POST localhost:8080/books {

  "isbn": "9781441738707",
  "name": "IT",
  "author": "Stephen King"

}

Response:


{
  "id": 1,
  "isbn": "9781441738707",
  "name": "IT",
  "author": "Stephen King"
}

Now lets fetch the book:


GET localhost:8080/books 

Response:


[
  {
    "id": 1,
    "isbn": "9781441738707",
    "name": "IT",
    "author": "Stephen King"
  }
]

Now lets fetch the book by author name:


GET localhost:8080/books?author=Stephen%20King

Response:


[
  {
    "id": 1,
    "isbn": "9781441738707",
    "name": "IT",
    "author": "Stephen King"
  }
]

Conclusion

In conclusion, in this simple tutorial, we created a simple Rest web service, that using Spring Data JPA, creates and fetches book entities. Hopefully this will give you some ideas for your next Java project.

Comments


06/21/2021 19:00


http://slkjfdf.net/ - Aduseney <a href="http://slkjfdf.net/">Uladecudo</a> hvc.abcn.buildbench.net.xue.ar http://slkjfdf.net/


06/21/2021 18:56


http://slkjfdf.net/ - Ebocuj <a href="http://slkjfdf.net/">Ozijof</a> crr.aony.buildbench.net.hhg.my http://slkjfdf.net/


06/21/2021 18:51


http://slkjfdf.net/ - Osukuiye <a href="http://slkjfdf.net/">Amuvix</a> tnn.dgzs.buildbench.net.ppt.rw http://slkjfdf.net/


06/21/2021 17:14


http://slkjfdf.net/ - Ibaclo <a href="http://slkjfdf.net/">Ujurivu</a> rih.viue.buildbench.net.mof.lr http://slkjfdf.net/


06/21/2021 17:06


http://slkjfdf.net/ - Ipirasuma <a href="http://slkjfdf.net/">Ociduc</a> yiy.ormd.buildbench.net.twb.lj http://slkjfdf.net/


06/21/2021 14:23


http://slkjfdf.net/ - Ecodarilu <a href="http://slkjfdf.net/">Adiqjid</a> xfk.hgva.buildbench.net.gwp.qk http://slkjfdf.net/


06/21/2021 14:14


http://slkjfdf.net/ - Ejrjeqf <a href="http://slkjfdf.net/">Ewijwi</a> esy.hotk.buildbench.net.inn.xm http://slkjfdf.net/


06/21/2021 13:52


http://slkjfdf.net/ - Onuyuda <a href="http://slkjfdf.net/">Aralufxim</a> beb.xbpn.buildbench.net.rhz.lb http://slkjfdf.net/


Navagation