Springboot from beginning II

Lahiru Sampath Abegunawardena
5 min readApr 28, 2020

Hi I’m lahiru Abegunawardena. This is the 2nd article on Java Springboot. If you did everything right as given in 1st article you should have a rest api that returns Hello world in http://localhost:8080/ by now. I have created a github repo for this project and this repo will be updated. You can check it and continue with this tutorial.

So today I’ll continue from the last point we finished. Today we will discuss about creating api to store data into database and retrieve all data from it. You will find springboot gives all of this in very easy progress. Always remember to restart application after code changes.

So in order to create a database connection first you need to add 2 more dependencies into pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

This is the 1st dependency we need. JPA is short term for “Java Persistent API”. It gives object-relational mapping. So we can use relational databases such as mysql databases. So next dependency is for mysql connection.

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

So we will see final outcome of our pom.xml as this.

adding dependencies for JPA and MySQl connection pom.xml

Usage of Application.properties

Now we need to create connection to database in our Springboot application. In order to do this we need a special file called application.properties in our src/main/resources folder and copy following lines into it.

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/springboot_blogdb
spring.datasource.username=root
spring.datasource.password=
spring.jpa.show-sql=true

Let's go through above properties one by one.

spring.jpa.hibernate.ddl-auto=update

There are four status that available for spring.jpa.hibernate.ddl-auto such as “create, update, create-drop, none, validate”.

create: Create the schema and deletes previous data (creates tables and removes data every time you run application)

update: Updates schema only if needs (Tables will be created only it needs, data will be not deleted)

create-drop: creates schema and it will delete when the session is end.

spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/springtrial_db

jdbc:mysql://${MYSQL_HOST:localhost}:db_port(3306)/db_name.

spring.jpa.show-sql=true

If this is true you will see executed sql queries through the application. You can remove this line if you don’t need it.

Books Api Collection introduction

So let’s start building our api. Once we finished this, we will be able to manage books. These are the api routes that we are going to create at end of this article series.

POST request http://localhost:8080/books/store : add Book.

GET request http://localhost:8080/books : Get all books

GET request http://localhost:8080/books/id : Get book by Id

PUT request http://localhost:8080/books/update/id : update Book

DELETE request http://localhost:8080/books/id: delete Book by Id.

Let’s look into Books table. We need to create a Bookmodel according Books table. So in this model file we initialise column name and data type. Let’s see how we can do this.

BookModel.java (Database Table/Entity model)

I have created a new Class named BookModel on new directory Books. I have added book_id, book_name, author_name and descriptrion. As you can see I have added two annotations @Entity, @Table(name=”book”). @entity is for notifying Springboot that this is a model class, in simple terms that is for identify this class as a table/entity in mysql and table name should be book (@Table(name=”book”)) and as you can see I have generated constructors, getters and setters.

I have annotated @Id to set book_id as primary key and by annotating “@GeneratedValue(strategy = GenerationType.AUTO)” springboot identifies it need to be autofilled automatically.

Now start your mysql server and create a db as you initialised in application.properties (I gave as springboot_blogdb) and run your springboot application you will see that table name

@RestController BookController

RestController example -> BookController

Let’s see what I’ve done in here.

@RestController: This is the annotation that we use in order to introduce this as a Controller class into SpringApplication.

@RequestMapping: I used this to add “books” as common part in above mentioned api collection. But I should mention that we can remove this and set @PostMapping(books/store) to accept a POST request that comes through localhost:8080/books/store url.

@PostMapping: this is the annotation we use to inform SpringAplication that this request should be a POST request.

@Autowired: This annotation is used to inject Class instances in Springboot.

@RequestBody: using this annotation we can get data that passed in request body in POST, PUT requests.

Repository Interface

CrudRepository

This is a interface class That we extend into CrudRepository interface. CrudRepository includes pre defined methods that can perform all sort of crud operations with Springboot. CrudRepository is a interface for generic operations on a repository for specific type. It needs to pass relevant entity class and data type for primary_key before extends this CrudRepository into your repository class.

public interface BookRepository extends CrudRepository<BookModel, Integer>

BookService: Business Service classes

@Service annotation is used to notify Bookservice that this is a BusinessService class. You can see that I used @Autowired annotation before injecting bookRepository instance. Using save method through bookRepository allows us to save data into “book” relation and this returns object of that saved data. So storeBooks method returns object of saved data.

So if you go step by step we can see that localhost:8080/books/store returns saved data according to data that we pass through body. So I added screenshot on POST response using Postman application.

Now I’ll show you breefly how to create another api endpoint to view all data in book relation.

Add this code into BookController

@GetMapping("")
public Iterable<BookModel> getAllBooks(){
return bookService.getAllBooks();

Then add following part into BookService class

public Iterable<BookModel> getAllBooks(){
return bookRepository.findAll();
}

So if you restart your application you will find that GET request on http://localhost:8080/books returns all books.

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 findingBookById, update and delete operations. I have updated repo with today code.

Try all of this by yourself and if there is anything feel free to comment. Like and Share with your friends. Here are my linkedin and fbpage. So you can contact me easily.

--

--