black and gray laptop computer turned on doing computer codes

Create a Simple Back-end Application with Spring Boot

Introduction

In this tutorial, you will learn how to create a simple back-end application with spring boot.

Back-end application is the core part of the full-stack web or mobile application. And also, it contains the logical and functional algorithm of the application. However, you can only access this application using client-side or front-end applications or through HTTP requests. However, if you want more information about the full-stack application you can visit this link: http://lgeratech.com/2019/11/what-is-a-full-stack-developer/

What you need

Generate Spring Boot Project

Create new ProductService project and click Next, On Spring Starter Project Dependencies dialog, select Lombok, Spring Boot DevTools, Spring Data JPA, H2 Database and Spring Web dependencies.

  • With selected Lombok, we don’t have to define codes for getter and setter, we only have to add one annotation which is provided by Lombok dependency. And also, it is commonly use for model class or DTO(Data Transfer Object) class.
  • We added Spring Data JPA to map object data from the database table row.
  • You can optionally add the H2 Database because, in this tutorial, I will provide database configuration for Embedded H2 database and MySQL database. however, you can only choose one type of database option.
  • We added Spring Web since it provides packages for a web application like Spring MVC and REST application.

Model Creation

In this section, we are going to create a Product entity to represent data that can be persisted to the database. Copy-paste the code below for the Product class:

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

import lombok.Data;

@Data
@Entity
public class Product {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Integer productId;
	private String productName;
	private String productDescription;
	private double productPrice;
	
}

As you can see, there is no getter and setter methods. Like I have mentioned in last section, we don’t have to define those methods, Lombok will do that for us. Which is by annotating the product class with @Data annotation.

Lombok also provides other annotations like @Getter, @Setter, @Builder, etc..

Database Setup

MySQL Setup

Here is the following steps to configure your MySQL database.

First, create a productDB database in MySQL. And you don’t have to create table for a product, Spring DATA JPA will generate that for you. Therefore, just copy-paste the configuration below to the application.properties file:

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/productDB?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create

By defining this property spring.jpa.hibernate.ddl-auto, we can tell to spring JPA on how it will manage the schema (table) on the database. The following values are:

validate: validate the schema, makes no changes to the database.
update: update the schema.
create: creates the schema, destroying previous data.
create-drop: drop the schema at the end of the session.

We used the create value to automatically generate a schema for us based on the entities(models) of our application. However, when you do not change the value from create to update value, the data will be destroyed when you restart the application.

To avoid that, you should update the spring.jpa.hibernate.ddl-auto to:

spring.jpa.hibernate.ddl-auto=update

However, if you already created a table for the product, you can directly use update value.

Embedded Database or H2 Database Setup

For the H2 database, you don’t have to define any configuration, because as a default, JPA will automatically detect it, when there is no database specified in application.properties.

However, when you restart the application, you will notice that the data is lost. It means, when the application is terminated, the database will back to zero.

Otherwise, we can avoid the data lost using file-based storage. Therefore, it can be done by defining spring.datasource.url in the application.properties file:

spring.datasource.url=jdbc:h2:file:./H2Database/productDB

You can find a database file that automatically generated inside of the project file.

However, If you want to view H2 database, you can use it built-in UI which is H2 console. Therefore, to configure and navigate to H2 console, visit this link: http://lgeratech.com/2020/06/spring-restful-with-jdbc-and-h2-database/#H2_console

Define CRUD operations using JPA Repositories

Here is the fastest and simple way to implement CRUD operations. In this section, we are going to create an interface that will handle CREATE, READ, UPDATE, and DELETE functions by a simple and short program.

Additionally, the JPA provides repositories that can handle CRUD operations. However, if you want to know more about JPA, you can visit this link: http://lgeratech.com/2020/06/implement-spring-data-jpa-in-restful-web-service/

Create a new file ProductRepository.java, and then copy-paste the code below:

import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface ProductRepository extends CrudRepository<Product, Integer>{
	List<Product> findAll();
}

For depth explanation about CrudRepository, visit this link: http://lgeratech.com/2020/06/implement-spring-data-jpa-in-restful-web-service/#Define_Query_using_JPA_Repository

Create a Controller

For the final procedure, let’s inject our ProductRepository in the ProductController class. However, If you missed the MVC controller tutorial you can visit this article for more information: http://lgeratech.com/2020/05/build-spring-mvc-application-using-spring-boot-framework/

@RestController
public class ProductController {	
	@Autowired
	ProductRepository productRepository;
	
	@PostMapping(value = "/createProduct")
	public ResponseEntity<String> createProduct(@RequestBody Product Product){
		productRepository.save(Product);
		return new ResponseEntity<String>("Product has been added succesfully", HttpStatus.OK);
	}
	
	@GetMapping(value = "/retrieveProducts")
	public ResponseEntity<List<Product>> retrieveProductList(){
		List<Product> Products = productRepository.findAll();
		return new ResponseEntity<List<Product>>(Products, HttpStatus.OK);
	}
	
	@GetMapping(value = "/Product/{productId}")
	public ResponseEntity<Product> getProducts(@PathVariable("productId") Integer productId){
		Optional<Product> product = productRepository.findById(productId);
		return new ResponseEntity<Product>(product.get(), HttpStatus.OK);
	}
	
	@PutMapping(value = "/updateProduct")
	public ResponseEntity<String> updateProduct(@RequestBody Product ProductRequest){
		Optional<Product> product = productRepository.findById(ProductRequest.getProductId());
		if(product.isPresent()) {
			product.get().setProductName(ProductRequest.getProductName());
			product.get().setProductDescription(ProductRequest.getProductDescription());
			product.get().setProductPrice(ProductRequest.getProductPrice());
			productRepository.save(product.get());
			return new ResponseEntity<String>("Product has been updated succesfully", HttpStatus.OK);
		}
		return new ResponseEntity<String>("Can't Find Product by id = " + ProductRequest.getProductId(), HttpStatus.BAD_REQUEST);
	}
	
	@DeleteMapping(value = "/deleteProduct/{id}")
	public ResponseEntity<String> deleteProduct(@PathVariable Integer id){
		Optional<Product> Product = productRepository.findById(id);
		if(Product.isPresent()) {
			productRepository.delete(Product.get());
			return new ResponseEntity<String>("Product has been deleted succesfully", HttpStatus.OK);
		}
		return new ResponseEntity<String>("Can't Find Product by id = " +  id, HttpStatus.BAD_REQUEST);
	}
}

As you can see, we annotated the ProductRepository with @Autowired annotation. Therefore, spring will recognize it as one of the dependencies of the ProductController class. And all of the functionality in ProductRepository, including CRUD operations, will be acquired to ProductController.

Launch the application

Skip this section if you already know how to execute the spring boot application.

You can now launch the application, using your eclipse, STS or using Cmd, in eclipse click the green icon  , then look for the WebRESTfulService, and then right click and click the (Re)start . In Cmd go to your project location then run this script ./mvnw spring-boot:run.

Run Test

However, If you don’t know how to test the RESTful application, which is the HTTP requests, you can refer to this tutorial: http://lgeratech.com/2020/05/building-a-restful-web-service-using-spring-boot/#Test_the_Application

Therefore, if you already know how to run it, here are the HTTP requests example that you can try:

POST Request: localhost:8080/createProduct
Request Body:
{	
	"productName":"Coffee",
	"productDescription": "Coffee is a brewed drink prepared from roasted coffee beans, the seeds of berries from certain Coffea species.",
    "productPrice": 100.00
	
}
GET Request: localhost:8080/retrieveProducts
PUT Request: localhost:8080/updateProduct
Request Body:
{
    "productId": 1,
    "productName": "Ice Coffee",
    "productDescription": "Coffee is a brewed drink prepared from roasted coffee beans, the seeds of berries from certain Coffea species.",
    "productPrice": 122.09
}

Conclusion

Congratulations! you finally create your back-end application.

For the next tutorial, we are going to create front-end application using HTML, CSS, JavaScript or Vanila JavaScript to interact with the back-end application.

You can get the project source code in github: https://github.com/LeoBernabe/product-service-v1

Leave a Reply

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

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.

BCF Theme By aThemeArt - Proudly powered by WordPress.
BACK TO TOP