Spring Boot REST example

Spring Boot Rest Example

Spring Boot REST example

In this tutorial, I will develop a simple spring boot rest service with the help of Spring Boot and Hibernate framework.

Spring Boot provides us the platform to develop REST APIs very quickly. A REST API is the most powerful and yet convenient way to publish data to different devices over the network. You can access and send the data by simply hitting the URL and you will be able to access the API on any device. You can manipulate the spring boot rest object even on client side by simply using Java Script language.

Before we begin

Before we begin, please make sure you understand the basics of web application development using Spring and Hibernate framework and you are able to create simple maven projects as well.

If you don’t have basic understanding of Spring and Hibernate framework then I will recommend you to please go through these good tutorials for beginners and professionals.

Spring Framework – Spring Tutorial
Hibernate Framework – Hibernate Tutorials
Spring MVC – Spring MVC

Create a Maven Web app project

First step off course is to create a simple maven project with web app archetype. Please use the below details for the maven project.

Group Id – com.springbootrest
Artifact Id – SpringBootRest


Project Structure



Spring Boot Rest Example




Add Maven Dependencies

We need to provide dependency details in order to use spring boot, hibernate framework. Maven is useful to manage dependencies as central repository.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.springbootrest</groupId>
 <artifactId>SpringBootRest</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>SpringBootRest Maven Webapp</name>
 <url>http://maven.apache.org</url>

 <parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>1.4.7.RELEASE</version>
 </parent>
 <properties>
 <java.version>1.7</java.version>
 </properties>
 <dependencies>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-jpa</artifactId>
 </dependency>
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 </dependency>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-devtools</artifactId>
 <optional>true</optional>
 </dependency>
 </dependencies>
 <build>
 <plugins>
 <plugin>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-maven-plugin</artifactId>
 </plugin>
 </plugins>
 </build>

</project>

Create Entity Model

Entity class represents the table in the database. Using this entity file, you will be able to query or fetch the data from the database using hibernate query.

BookDetails.java

package com.springbootrest.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "boot_details")
public class BookDetails {

 @Id
 @GeneratedValue(strategy = GenerationType.AUTO)
 @Column(name="id")
 private int id;
 
 @Column(name="name")
 private String name;
 
 @Column(name="author")
 private String author;

 public int getId() {
 return id;
 }

 public void setId(int id) {
 this.id = id;
 }

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getAuthor() {
 return author;
 }

 public void setAuthor(String author) {
 this.author = author;
 }

}

Create Repository

Now we will create separate repository files in order to fetch or query the data from the database using Hibernate query language.

@PersistenceContext – We need to understand how we are able to connect with the database using just simple annotation @PersistenceContext and what it is.

  1. Entities are managed by javax.persistence.EntityManager instance using persistence context.
  2. Each EntityManager instance is associated with a persistence context.
  3. Within the persistence context, the entity instances and their lifecycle are managed.
  4. Persistence context defines a scope under which particular entity instances are created, persisted, and removed.
  5. A persistence context is like a cache which contains a set of persistent entities , So once the transaction is finished, all persistent objects are detached from the EntityManager’s persistence context and are no longer managed.

Let’s create an interface for our operations.


BookDetailsRepo.java
package com.springbootrest.repository;

import java.util.List;

import com.springbootrest.model.BookDetails;

public interface BookDetailsRepo {

 List<BookDetails> listBookDetails();
}


BookDetailsRepoImpl.java

package com.springbootrest.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.springframework.stereotype.Repository;

import com.springbootrest.model.BookDetails;

@Transactional
@Repository
public class BookDetailsRepoImpl implements BookDetailsRepo {

 @PersistenceContext
 private EntityManager entityManager;
 
 public List<BookDetails> listBookDetails() {
 return (List<BookDetails>) entityManager.createQuery("FROM BookDetails").getResultList();
 }

}

Now Create separate service layer

The main function of the service layer is to fetch the data from the DAO or repository layer. The main benefit of using service layer is that we can define more than one method to access the same data. 

BookDetailsService.java

package com.springbootrest.service;

import java.util.List;

import com.springbootrest.model.BookDetails;

public interface BookDetailsService {
 
 List<BookDetails> listBookDetails();
}

BookDetailsServiceImpl.java
package com.springbootrest.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.springbootrest.model.BookDetails;
import com.springbootrest.repository.BookDetailsRepo;

@Service
public class BookDetailsServiceImpl implements BookDetailsService {

 @Autowired
 private BookDetailsRepo bookDetailsRepo;
 
 public List<BookDetails> listBookDetails() {
 return bookDetailsRepo.listBookDetails();
 }

}

Finally create the Controller to use the service

Finally we will create separate controller which will define REST service. We are using ResponseEntity which is used to create entire HTTP response or represent the HTTP response.

RestController.java

package com.springbootrest.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.springbootrest.model.BookDetails;
import com.springbootrest.service.BookDetailsService;

@Controller
@RequestMapping("book")
public class RestController {

 @Autowired
 private BookDetailsService bookDetailsService;

 @GetMapping("listBook")
 public ResponseEntity<List<BookDetails>> listBookDetails() {
 List<BookDetails> list = bookDetailsService.listBookDetails();
 return new ResponseEntity<List<BookDetails>>(list, HttpStatus.OK);
 }
}

Define the property for the application

Application property file is used to define central configuration which can be used by the run the application. You don’t need to change the configuration everywhere.

Please note – You can provide ddl-auto = create for the first time if you did not create any database or table manually which will create them for you automatically. After that you can set it to ddl-auto = none.

application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springbootrest
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.min-idle=15

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true

spring.jpa.hibernate.ddl-auto=none

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE 

Create Application runner

Spring boot application runner configure application for you automatically and run the application.

SpringBootRestApplication.java

package com.springbootrest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableAutoConfiguration
public class SpringBootRestApplication {

 public static void main(String[] args) {
 SpringApplication.run(SpringBootRestApplication.class, args);
 }
}



Finally run the application

You should be able to see the below output.


Spring Boot REST Hibernate

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *