SpringBoot MariaDB CRUD RestAPI Example
Tags: springboot, crud, mariadb, restapi
Published: 2021-05-19 16:19:36

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:
<ul style="margin-left:20px" id="to-do-list-how-to-integrate-springboot-and-postgresql-using-spring-jpa-loizenai.com">
<li>Overview of Project Structure</li>
<li>Create SpringBoot with Spring Data JPA and MariaDB dependencies</li>
<li>Configuration SpringBoot to connect to MariaDB</li>
<li>Define a data model to map with table's columns in MariaDB database</li>
<li>Define a JPA Repository to do CRUD operations</li>
<li>Use CommandLineRunner to excute above JPA Repository APIs: save, retrieve, update, detele entities</li>
</ul>

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

Let's go !
<!--more-->
<h2 id="video-guide-for-how-to-integrate-springboot-with-postgresql-database-tutorial">Video Guide</h2>
<iframe width="560" height="315" src="https://www.youtube.com/embed/YosqvdsJ4aM?controls=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<h2 id="springboot-project-overview">SpringBoot Project Overview</h2>
[caption id="attachment_56" align="alignnone" width="378"]<img src="https://loizenai.com/wp-content/uploads/2020/04/Overview-How-to-Integrate-Springboot-2.x-with-PostgreSQL-using-Spring-JPA.png" alt="SpringBoot-PostgreSQL-CRUD-Example-Overview-How-to-Integrate-Springboot-2.x-with-PostgreSQL-using-Spring-JPA" width="378" height="507" class="size-full wp-image-56" /> 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.
<h2 id="create-springboot-project">Create SpringBoot Project</h2>
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 <code>pom.xml</code> file we see the needed dependencies as below:


<pre><code class="language-html">&lt;dependency&gt;
	&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
	&lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.mariadb.jdbc&lt;/groupId&gt;
    &lt;artifactId&gt;mariadb-java-client&lt;/artifactId&gt;
    &lt;version&gt;2.1.0&lt;/version&gt;
&lt;/dependency&gt;</code></pre>

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

[caption id="attachment_135" align="alignnone" width="551"]<img src="https://loizenai.com/wp-content/uploads/2020/04/springboot-project-structure.png" alt="SpringBoot MariaDB CRUD Example - Springboot project structure" width="551" height="371" class="size-full wp-image-135" /> SpringBoot project structure[/caption]
<h2 id="setup-springboot-datasource">Setup SpringBoot datasource for connecting with MariaDB</h2>
SpringBoot helps us to create a datasource by simple configuration in <code>application.properties</code> file. We use the <code>spring.datasource.*</code> to setup the <code>url</code>, <code>username</code> and <code>password</code> for Spring datasource bean as above.

<pre><code class="language-html">
## MariaDB
spring.datasource.url=jdbc:mariadb://localhost:3306/jsadb
spring.datasource.username=root
spring.datasource.password=12345
spring.jpa.hibernate.ddl-auto=create-drop
</code></pre>
<h2 id="create-spring-data-model-class">How to create a Spring data model class?</h2>
Imagine that we have a <code>customer</code> 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.

<pre><code class="language-java">
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);	
	}
}</code></pre>

<code>@Entity</code> specifies that the class is an entity. This annotation is applied to the entity class.
<code>@Table</code> specifies the primary table for the annotated entity. 
<code>@Column</code> specifies the mapped column for a persistent property or field.
<code>@Id</code> specifies the primary key of an entity.
<code>@GeneratedValue</code> 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 <code>Customer</code>, we defines 2 constructors:
- The default constructor <code>protected Customer() {}</code> is used only by Spring JPA and we will not directly to use it so we define the constructor with <code>protected</code>
- With the second constructor <code>public Customer(String firstname, String lastname, int age)</code>, we use to create a Customer instance, so we define it with all properties of Customer class as parameters.

We also create a <code>toString</code> method that is used to print all property values of a customer instance on console for checking.
<h2 id="create-spring-jpa-crud-repository-to-do-crud-operations">Create Spring JPA Repository to do CRUD operations</h2>
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]

- <code>Repository</code> 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.
<pre><code class="language-java">@Indexed
public interface Repository&lt;T, ID&gt; {
}</code></pre>


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

SpringBoot MariaDB CRUD RestAPI Example