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

55 thoughts on “MariaDB – How to use Spring JPA MariaDB by Spring Boot”

  1. I must voice my affection for your kindness supporting people who must have guidance on your concept. Your personal commitment to getting the message all over had become extremely helpful and have empowered guys and women much like me to attain their objectives. Your new insightful guidelines indicates a lot a person like me and a whole lot more to my office colleagues. Many thanks; from each one of us.

    Rankcircles.com

  2. My brother recommended I may like this website. He was totally right. This put up actually made my day. You can not consider just how a lot time I had spent for this information! Thank you!

  3. hey there and thank you to your information ?I have definitely picked up anything new from proper here. I did alternatively expertise a few technical points using this web site, as I skilled to reload the website lots of instances prior to I may just get it to load correctly. I were thinking about if your web hosting is OK? Now not that I am complaining, but slow loading instances times will often affect your placement in google and can injury your high quality ranking if advertising and ***********|advertising|advertising|advertising and *********** with Adwords. Well I am adding this RSS to my e-mail and could glance out for a lot extra of your respective exciting content. Ensure that you replace this once more soon..

  4. I’m truly enjoying the design and layout of your blog. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a designer to create your theme? Superb work!

  5. certainly like your web site but you have to check the spelling on quite a few of your posts. Several of them are rife with spelling issues and I find it very troublesome to tell the truth nevertheless I will surely come back again.

  6. Heya just wanted to give you a quick heads up and let you know a few of the pictures aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different internet browsers and both show the same outcome.

  7. Excellent items from you, man. I’ve keep in mind your stuff previous to and you are just extremely great. I really like what you’ve acquired right here, certainly like what you’re saying and the best way through which you say it. You are making it enjoyable and you still take care of to stay it sensible. I cant wait to read far more from you. This is really a wonderful web site.

  8. Hey! I just wanted to ask if you ever have any issues with hackers? My last blog (wordpress) was hacked and I ended up losing months of hard work due to no back up. Do you have any methods to protect against hackers?

  9. I cherished up to you will obtain performed proper here. The caricature is attractive, your authored subject matter stylish. nonetheless, you command get bought an impatience over that you would like be delivering the following. in poor health unquestionably come further formerly once more since exactly the same nearly very often inside case you shield this increase.

  10. I should say also believe that mesothelioma is a extraordinary form of cancer that is commonly found in these previously exposed to asbestos. Cancerous cellular material form inside mesothelium, which is a protecting lining which covers most of the body’s internal organs. These cells generally form while in the lining in the lungs, belly, or the sac that really encircles one’s heart. Thanks for discussing your ideas.

  11. Thank you for sharing excellent informations. Your web site is very cool. I am impressed by the details that you have on this site. It reveals how nicely you understand this subject. Bookmarked this website page, will come back for more articles. You, my friend, ROCK! I found simply the information I already searched all over the place and just could not come across. What an ideal web site.

  12. Thank you, I have just been searching for information approximately this topic for ages and yours is the best I’ve found out till now. But, what concerning the conclusion? Are you sure concerning the source?

  13. A lot of thanks for all of the effort on this web site. Kate enjoys going through investigation and it’s obvious why. My partner and i hear all relating to the lively tactic you give both useful and interesting steps through this website and strongly encourage contribution from some others about this concern and our favorite girl is really being taught a whole lot. Enjoy the remaining portion of the year. Your performing a fabulous job.

  14. Hello there, simply changed into aware of your blog through Google, and located that it’s really informative. I’m gonna watch out for brussels. I will be grateful in case you proceed this in future. A lot of folks can be benefited out of your writing. Cheers!

  15. I have mastered some new things from your web page about computer systems. Another thing I have always thought is that laptop computers have become something that each house must have for several reasons. They provide convenient ways to organize households, pay bills, search for information, study, pay attention to music and in many cases watch tv programs. An innovative approach to complete all of these tasks is to use a laptop. These computers are mobile ones, small, strong and lightweight.

  16. Today, I went to the beach with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is entirely off topic but I had to tell someone!

  17. I’ve really noticed that credit restoration activity really needs to be conducted with tactics. If not, you might find yourself endangering your rank. In order to be successful in fixing your credit rating you have to confirm that from this instant you pay all of your monthly costs promptly in advance of their planned date. It is definitely significant on the grounds that by never accomplishing that, all other activities that you will take to improve your credit ranking will not be successful. Thanks for sharing your thoughts.

  18. My spouse and i felt so relieved Michael managed to finish off his research because of the ideas he gained from your web site. It’s not at all simplistic just to choose to be giving freely key points the rest have been trying to sell. And we also acknowledge we have you to give thanks to because of that. The main explanations you’ve made, the easy blog navigation, the relationships you can help engender – it’s many excellent, and it’s aiding our son in addition to our family feel that that concept is thrilling, and that is extremely serious. Many thanks for the whole thing!

  19. Hello! I know this is kinda off topic but I was wondering which blog platform are you using for this site? I’m getting sick and tired of WordPress because I’ve had issues with hackers and I’m looking at options for another platform. I would be fantastic if you could point me in the direction of a good platform.

  20. Thanks for your write-up. One other thing is when you are selling your property on your own, one of the problems you need to be mindful of upfront is just how to deal with property inspection reviews. As a FSBO owner, the key about successfully transferring your property and saving money on real estate agent commission rates is knowledge. The more you are aware of, the softer your home sales effort are going to be. One area exactly where this is particularly critical is home inspections.

  21. Thanks for your interesting article. Other thing is that mesothelioma is generally caused by the breathing of materials from mesothelioma, which is a dangerous material. It’s commonly observed among laborers in the structure industry who’ve long experience of asbestos. It could be caused by moving into asbestos protected buildings for an extended time of time, Genetics plays a huge role, and some folks are more vulnerable for the risk compared to others.

  22. Thanks for enabling me to gain new strategies about pcs. I also hold the belief that one of the best ways to help keep your laptop computer in prime condition is a hard plastic case, or perhaps shell, that suits over the top of one’s computer. Most of these protective gear will be model unique since they are made to fit perfectly within the natural housing. You can buy them directly from the seller, or from third party sources if they are available for your laptop, however only a few laptop could have a cover on the market. Once more, thanks for your guidelines.

  23. I think this is among the most significant info for me. And i am glad reading your article. But wanna remark on few general things, The web site style is wonderful, the articles is really excellent : D. Good job, cheers

  24. I am extremely impressed with your writing skills and also with the layout on your blog. Is this a paid theme or did you customize it yourself? Either way keep up the nice quality writing, it抯 rare to see a great blog like this one these days..

  25. Thanks for the sensible critique. Me and my neighbor were just preparing to do some research on this. We got a grab a book from our area library but I think I learned more from this post. I am very glad to see such fantastic information being shared freely out there.

  26. It is the best time to make some plans for the longer term and it is time to be happy. I have read this post and if I may just I wish to recommend you some attention-grabbing things or suggestions. Perhaps you could write next articles referring to this article. I wish to learn even more issues approximately it!

  27. I抦 impressed, I need to say. Actually rarely do I encounter a blog that抯 both educative and entertaining, and let me let you know, you have hit the nail on the head. Your thought is excellent; the issue is something that not enough people are talking intelligently about. I am very glad that I stumbled throughout this in my search for one thing referring to this.

  28. One other issue is when you are in a circumstances where you do not possess a cosigner then you may actually want to try to wear out all of your money for college options. You will find many awards and other free college funding that will give you funding to aid with school expenses. Thanks alot : ) for the post.

  29. I just like the valuable info you supply for your articles. I抣l bookmark your weblog and take a look at once more here frequently. I am moderately certain I抣l be informed many new stuff right here! Best of luck for the following!

  30. It’s a pity you don’t have a donate button! I’d most certainly donate to this brilliant blog!
    I suppose for now i’ll settle for book-marking and adding
    your RSS feed to my Google account. I look forward to fresh updates and will talk about this
    blog with my Facebook group. Chat soon!

  31. Thank you a bunch for sharing this with all people you really
    realize what you are talking approximately! Bookmarked.
    Please also visit my website =). We could have
    a hyperlink change agreement between us

  32. What i don’t realize is actually how you are now not actually a lot more smartly-appreciated than you might be now. You’re very intelligent. You recognize thus significantly in the case of this topic, made me individually consider it from numerous varied angles. Its like women and men don’t seem to be interested except it¦s something to accomplish with Lady gaga! Your individual stuffs excellent. At all times maintain it up!

  33. It’s a pity you don’t have a donate button! I’d most certainly donate to this excellent blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to brand new updates and will talk about this site with my Facebook group. Talk soon!

  34. I really like your blog.. very nice colors & theme. Did you
    create this website yourself or did you hire someone to do it for you?

    Plz reply as I’m looking to construct my own blog and would like to know where u got
    this from. cheers

Leave a Reply

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