DEV Community

loizenai
loizenai

Posted on

SpringBoot MariaDB CRUD RestAPI Example

https://loizenai.com/springboot-mariadb-crud-restapi-example/

SpringBoot MariaDB CRUD RestAPI Example

  • Example Integrate SpringBoot 2.x + MariaDB CRUD using Spring JPA tutorial

How to integrate SpringBoot and MariaDB? It is the one of most common questions for developers. So in the post, I will help you to try it with Spring JPA. Here is a to do list for the tutorial:

  • Overview of Project Structure
  • Create SpringBoot with Spring Data JPA and MariaDB dependencies
  • Configuration SpringBoot to connect to MariaDB
  • Define a data model to map with table's columns in MariaDB database
  • Define a JPA Repository to do CRUD operations
  • Use CommandLineRunner to excute above JPA Repository APIs: save, retrieve, update, detele entities

To do the tutorial, you need prepare Java >= 1.8, Spring Tool Suite in local computer for development.

Let's go !

Video Guide

SpringBoot Project Overview

[caption id="attachment_56" align="alignnone" width="378"]SpringBoot-PostgreSQL-CRUD-Example-Overview-How-to-Integrate-Springboot-2.x-with-PostgreSQL-using-Spring-JPA Project Overview How to Integrate Springboot 2.x with MariaDB using Spring JPA[/caption]

In the SpringBoot application, we use Spring JPA to connect and manipulate the data between Application and MariaDB database. We define a repository to do CRUD operations (save, retrieve, update, delete) with entities. And for mapping the data between Spring Application with database table's columns, we define a model class.

Create SpringBoot Project

We use Eclipse that had integrated with SpringToolSuite to create a SpringBoot project. Remember we need add 2 dependencies Spring Data JPA and MariaDB driver.

Checking pom.xml file we see the needed dependencies as below:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.mariadb.jdbc</groupId>
    <artifactId>mariadb-java-client</artifactId>
    <version>2.1.0</version>
</dependency>

Now we implement a SpringBoot Application to manipulate data with MariaDB database.

[caption id="attachment_135" align="alignnone" width="551"]SpringBoot MariaDB CRUD Example - Springboot project structure SpringBoot project structure[/caption]

Setup SpringBoot datasource for connecting with MariaDB

SpringBoot helps us to create a datasource by simple configuration in application.properties file. We use the spring.datasource.* to setup the url, username and password for Spring datasource bean as above.


## MariaDB
spring.datasource.url=jdbc:mariadb://localhost:3306/jsadb
spring.datasource.username=root
spring.datasource.password=12345
spring.jpa.hibernate.ddl-auto=create-drop

How to create a Spring data model class?

Imagine that we have a customer table in MariaDB database with 4 columns:
{id, firstname, lastname, age}

How to map the data between SpringBoot application with these table's columns for manipulating data? We need create a Customer model class having 4 properties {id, firstname, lastname, age} then use annotations to handle the mapping each columns of tables which corresponding properties in java model class.


package com.loizenai.postgresqlspringboot.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="customer")
public class Customer {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    
    @Column(name="firstname")
    private String firstname;
    
    @Column(name="lastname")
    private String lastname;
    
    @Column(name="age")
    private int age;

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    
    protected Customer() {}
    
    public Customer(String firstname, String lastname, int age) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.age = age;
    }
    
    public String toString() {
        return String.format("id=%d, firstname='%s', lastname'%s', age=%d", 
                                id, firstname, lastname, age);  
    }
}

@Entity specifies that the class is an entity. This annotation is applied to the entity class.
@Table specifies the primary table for the annotated entity.
@Column specifies the mapped column for a persistent property or field.
@Id specifies the primary key of an entity.
@GeneratedValue provides for the specification of generation strategies for the values of primary keys. The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation. The use of the GeneratedValue annotation is only required to be supported for simple primary keys. Use of the GeneratedValue annotation is not supported for derived primary keys.

In the model data class Customer, we defines 2 constructors:

  • The default constructor protected Customer() {} is used only by Spring JPA and we will not directly to use it so we define the constructor with protected
  • With the second constructor public Customer(String firstname, String lastname, int age), we use to create a Customer instance, so we define it with all properties of Customer class as parameters.

We also create a toString method that is used to print all property values of a customer instance on console for checking.

Create Spring JPA Repository to do CRUD operations

In the tutorial "SpringBoot MariaDB CRUD", for easy to manipulate data with MariaDB, Spring JPA provides interface APIs to do the works. Here is the hierarchy structure of Spring JPA Repository:

[caption id="attachment_140" align="alignnone" width="672"]<img src="https://loizenai.com/wp-content/uploads/2020/04/spring-jpa-crud-repository-hierarchy-structure.png" alt="SpringBoot MariaDB CRUD Example

  • Repository Hierarchy Structure" width="672" height="219" class="size-full wp-image-140" /> Spring JPA CRUD Repository Hierarchy[/caption]

    • Repository is central repository marker interface. Captures the domain type to manage as well as the domain type's id type. General purpose is to hold type information as well as being able to discover interfaces that extend this one during classpath scanning for easy Spring bean creation.

Domain repositories extending this interface can selectively expose CRUD methods by simply declaring methods of the same signature as those declared in CrudRepository.

@Indexed
public interface Repository<T, ID> {
}

More at:
https://loizenai.com/springboot-mariadb-crud-restapi-example/

SpringBoot MariaDB CRUD RestAPI Example

Top comments (0)