Create APIs with Spring Boot & MYSQL database

 In the previous tutorial, you learnt to create and run Spring Boot spring-tutorial project in VS Code. Now we move on connecting to MYSQL database and creating APIs to perform CRUD operations.

First modify the src/main/resources/application.properties file to add database credentials as below:

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/database_name
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

We specify spring.jpa.hibernate.ddl-auto=update to automatically update the schema to add new additions upon startups. 
Then update the pom.xml configuration file to add required dependencies - JPA and MYSQL Connector to work with MYSQL database:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.dev</groupId>
    <artifactId>spring-tutorial</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-tutorial</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


In the springtutorial folder, create models folder. In the models folder, create Product entity. We use @Entity annotation to specify that the class is an entity. The entity has four attributes: id, name, price, and thumbnail (image file name).

package com.dev.springtutorial.models;

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

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    private float price;
    private String thumbnail;

   
    public Product() {
        this.id=0;
        this.name="";
        this.price=0.0f;
        this.thumbnail="";
    }
    public Product(int id,String name,float price,String thumbnail) {
        this.id=id;
        this.name=name;
        this.price=price;
        this.thumbnail=thumbnail;
    }
    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 float getPrice() {return price;}
    public void setPrice(float price) {
        this.price=price;
    }
    public String getThumbnail() {
        return thumbnail;
    }
    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }
}

Create repos folder in springtutorial and add the ProductReposity.java file. TheProductReposity use CrudReposity to allow CRUD operation on Prouct entity.

package com.dev.springtutorial.repos;
import org.springframework.data.repository.CrudRepository;
import com.dev.springtutorial.models.Product;

// CRUD refers Create, Read, Update, Delete
public interface ProductRepository extends CrudRepository<Product, Integer> {

}

After that, create controllers folder in springtutorial and add ProductController.java file. The ProductController handles requests and responses. 

package com.dev.springtutorial.controllers;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dev.springtutorial.models.Product;
import com.dev.springtutorial.repos.ProductRepository;

@Controller // This means that this class is a Controller
@RequestMapping("/products") // map web requests to http://localhost:8080/products
public class ProductController {

  @Autowired // inject ProductRepository dependency
  private ProductRepository productRepository;

 
  @PostMapping("/add") // map POST method Requests on path products/add
  public @ResponseBody Product addPro (@RequestBody Product product) {
    //RequestBody contain request data {id,name,price,thumbnail}
    productRepository.save(product);
    return product;
  }
 
  @PutMapping("/update/{id}") // map PUT method Requests on path products/update/{id}
  public @ResponseBody Product updatePro (@PathVariable int id,@RequestBody Product product) {

    // @PathVariable means it is a parameter from the request URL
    product.setId(id);
    productRepository.save(product);

    return product;
  }
  @DeleteMapping("/delete/{id}") // map DELETE method Requests on path products/delete/{id}
  public @ResponseBody void deletePro (@PathVariable int id) {
    // @ResponseBody means the returned String is the response, not a view name
  // @PathVariable means it is a parameter from the request URL
    productRepository.deleteById(id);
   
  }

  @GetMapping("/all") // map GET method request on path products/all
  public @ResponseBody Iterable<Product> getAllProducts() {
    // This returns a JSON  with the products
    return productRepository.findAll();
  }
}

While MYSQL Server is running, run the project (Ctrl+F5). The product table should be created in the database. 
Let start testing the APIs using ARC chrome extension. 

Add product: 



List all products:

Update product:



Comments