MariaDB – How to use Spring JPA MariaDB by Spring Boot

In tradition approach, implementing Data Access Layer makes lots of boilerplate code. Spring JPA is a part of Spring Data, helps us improve our codes and reduce efforts for development and maintenance. Spring JPA supports us the ways to write interface for repositories and custom finder methods, the implementation will be done automatically by Spring Framework.
About MariaDB, it is an open source leader, provides the solutions to run on all infrastructure.

So in the tutorial, JavaSampleApproach shows you how to create Spring JPA MariaDB application using Spring Boot.

Related posts:
How to use Spring JPA with PostgreSQL | Spring Boot
How to use Spring JPA MySQL | Spring Boot

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.6RELEASE
– MariaDB 10.2.7

II. Overview

1. Goal

spring boot spring jpa - mariadb - architecture

2. Project Structure

spring jpa mariadb - project structure

3. Step to do

– Create Spring Boot project
– Create DataModel Class
– Create Spring JPA Repository Interface
– Create Web Controller
– Deployment

III. Practice

1. Create Spring Boot project

Open Spring Tool Suite, on Menu, choose File -> New -> Spring Starter Project, then input project’s info. Press Next then Finish, a Spring Boot project will be created successfully.

Open pom.xml, add needed dependencies: Spring JPA, Web, Mariadb Client:

<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>org.mariadb.jdbc</groupId>
    <artifactId>mariadb-java-client</artifactId>
    <version>2.1.0</version>
</dependency>

2. Create DataModel Class

Under package model, create class Customer:

package com.javasampleapproach.mariadb.model;

import java.io.Serializable;

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 implements Serializable {

	private static final long serialVersionUID = -3009157732242241606L;
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private long id;

	@Column(name = "firstname")
	private String firstName;

	@Column(name = "lastname")
	private String lastName;

	protected Customer() {
	}

	public Customer(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return String.format("Customer[id=%d, firstName='%s', lastName='%s']", id, firstName, lastName);
	}
}

Annotation @Entity indicates that Customer is an Entity and @Table specifies the primary table (name customer) for the annotated @Entity.

@ID specifies the primary key and @GeneratedValue indicates generation strategy for value of primary key.

@Column: mapped column (in the table) for persistent fields (in Java class).

We have 2 constructor methods:
– protected constructor will be used by Spring JPA.
– public constructor is for creating instances.

3. Create Spring JPA Repository Interface

This interface helps us do all CRUD functions for class Customer.

package com.javasampleapproach.mariadb.repo;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

import com.javasampleapproach.mariadb.model.Customer;


public interface CustomerRepository extends CrudRepository{
	List findByLastName(String lastName);
}

Open application.properties, configure spring.datasource and spring.jpa:

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

4. Create Web Controller

The controller receives requests from client, using repository to update/get data and return results.

Content of WebController.java:

package com.javasampleapproach.mariadb.controller;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.javasampleapproach.mariadb.model.Customer;
import com.javasampleapproach.mariadb.repo.CustomerRepository;

@RestController
public class WebController {
	
	@Autowired
	CustomerRepository repository;
	
	@GetMapping("/save")
	public String process(){
		
		repository.save(Arrays.asList(new Customer("Jack", "Smith"), 
										new Customer("Adam", "Johnson"),
										new Customer("Kim", "Smith"),
										new Customer("David", "Williams"),
										new Customer("Peter", "Davis")));
		
		return "Done";
	}
	
	
	@GetMapping("/findall")
	public String findAll(){
		
		String result = "";
		
		for(Customer cust : repository.findAll()){
			result += cust + "
"; } return result; } @GetMapping("/findbyid") public String findById(@RequestParam("id") long id){ String result = ""; result = repository.findOne(id).toString(); return result; } @GetMapping("/findbylastname") public String fetchDataByLastName(@RequestParam("lastname") String lastName){ String result = ""; for(Customer cust: repository.findByLastName(lastName)){ result += cust + "
"; } return result; } }

In the web controller methods which are annotated by @GetMapping, we have used some methods of autowired repository which are implemented interface CrudRepository:

<S extends T> Iterable<S> save(Iterable<S> entities); //for @GetMapping("/save")
T findOne(ID id); //for @GetMapping("/findbyid")
Iterable<T> findAll(); //for @GetMapping("/findall")

and the method findByLastName that we create in our interface CustomerRepository.

List<Customer> findByLastName(String lastName);

5. Deployment

Open MariaDB client, create jsadb database:

create database jsadb

Then creating customer table:

> use jsadb;

> CREATE TABLE customer(
    id INT NOT NULL AUTO_INCREMENT,
    firstname VARCHAR(20) NOT NULL,
    lastname VARCHAR(20) NOT NULL,
	PRIMARY KEY (id)
);

spring jpa  mariadb create table

Build and Run the SpringBoot project with commandlines: {mvn clean install, mvn spring-boot:run}.

Make requests:

– Request 1: http://localhost:8080/save:

spring jpa - mariadb select all

– Request 2: http://localhost:8080/findall:

springboot jpa mariadb - select all request

– Request 3: http://localhost:8080/findbyid?id=1

springboot jpa mariadb - select one customer

– Request 4: http://localhost:8080/findbylastname?lastname=Smith

springboot jpa mariadb - find customer by lastname

III. Sourcecode

SpringBootJPAMariaDB

0 0 votes
Article Rating
Subscribe
Notify of
guest
4.4K Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments