How to use Spring JPA MySQL | Spring Boot

In tradition approach, implementing Data Access Layer makes lots of boilerplate of 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.

In the tutorial, JavaSampleApproach will show you way to use Spring JPA MySQL using Spring Boot.

Related articles:
How to access MySQL database with Spring Data Rest application
Angular 4 + Spring JPA + MySQL example | Angular 4 Http Client – Spring Boot RestApi Server
React Redux + Spring Boot + MySQL CRUD example
Spring Boot + Angular 6 example | Spring Data JPA + REST + MySQL CRUD example

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.4.3.RELEASE

II. Overview
1. Project Structure

springboot  spring jpa mysql project overview

2. Step to do

– Create Spring Boot project & add Dependencies
– Configure Spring JPA
– Create DataModel Class
– Create Spring JPA Repository Interface
– Create Web Controller
– Create MySQL table
– Run Spring Boot Application & Enjoy Result

III. Practice
1. Create Spring Boot project & add Dependencies

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 MVC, MySQL Connector


	org.springframework.boot
	spring-boot-starter-data-jpa


	org.springframework.boot
	spring-boot-starter-web

	

    mysql
    mysql-connector-java

2. Configure Spring JPA

Open application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/testdb
spring.datasource.username=root
spring.datasource.password=12345
spring.jpa.generate-ddl=true
3. Create DataModel Class

Under package model, create class Customer.

package com.javasampleapproach.mysql.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.

4. Create Spring JPA Repository Interface

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

package com.javasampleapproach.mysql.repository;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

import com.javasampleapproach.mysql.model.Customer;

public interface CustomerRepository extends CrudRepository{
    List findByLastName(String lastName);
}
5. 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.mysql.controller;

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

import com.javasampleapproach.mysql.model.Customer;
import com.javasampleapproach.mysql.repository.CustomerRepository;

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

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

 S save(S entity); //for @RequestMapping("/save")
T findOne(ID id); //for @RequestMapping("/findbyid")
Iterable findAll(); //for @RequestMapping("/findall")

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

List findByLastName(String lastName);
6. Create MySQL table
CREATE TABLE customer(
   id INT NOT NULL AUTO_INCREMENT,
   firstname VARCHAR(20) NOT NULL,
   lastname VARCHAR(20) NOT NULL,
   PRIMARY KEY (id)
);
7. Run Spring Boot Application & Enjoy Result

– Config maven build: clean install
– Run project with mode Spring Boot App
– Check results:
Request 1: http://localhost:8080/save
The browser returns Done and if checking database testdb with table customer, we can see some data rows has been added:
springboot spring jpa mysql

Request 2: http://localhost:8080/findall
springboot spring jpa mysql findall

Request 3: http://localhost:8080/findbyid?id=4
springboot spring jpa mysql findbyid

Request 4: http://localhost:8080/findbylastname?lastname=Smith
springboot spring jpa mysql findbylastname

III. Sourcecode

SpringJPA-MySQL



By grokonez | January 5, 2017.

Last updated on February 6, 2020.



Related Posts


4 thoughts on “How to use Spring JPA MySQL | Spring Boot”

  1. Hi Team,

    Kindly help for me. i want fix this issue.

    2018-03-13 15:36:28.465 INFO 2600 — [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ‘characterEncodingFilter’ to: [/*]
    2018-03-13 15:36:28.466 INFO 2600 — [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ‘hiddenHttpMethodFilter’ to: [/*]
    2018-03-13 15:36:28.467 INFO 2600 — [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ‘httpPutFormContentFilter’ to: [/*]
    2018-03-13 15:36:28.470 INFO 2600 — [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: ‘requestContextFilter’ to: [/*]
    2018-03-13 15:36:28.571 WARN 2600 — [ main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization – cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘webController’: Unsatisfied dependency expressed through field ‘repository’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘customerRepository’: Cannot create inner bean ‘(inner bean)#11b455e5’ of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property ‘entityManager’; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘(inner bean)#11b455e5’: Cannot resolve reference to bean ‘entityManagerFactory’ while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘entityManagerFactory’ available
    2018-03-13 15:36:28.575 INFO 2600 — [ main] o.apache.catalina.core.StandardService : Stopping service Tomcat
    2018-03-13 15:36:28.588 WARN 2600 — [ost-startStop-1] o.a.c.loader.WebappClassLoaderBase : The web application [ROOT] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
    java.lang.Object.wait(Native Method)
    java.lang.ref.ReferenceQueue.remove(Unknown Source)
    com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:43)
    2018-03-13 15:36:28.604 INFO 2600 — [ main] utoConfigurationReportLoggingInitializer :

    Error starting ApplicationContext. To display the auto-configuration report re-run your application with ‘debug’ enabled.
    2018-03-13 15:36:28.727 ERROR 2600 — [ main] o.s.b.d.LoggingFailureAnalysisReporter :

    ***************************
    APPLICATION FAILED TO START
    ***************************

    Description:

    Field repository in com.javasampleapproach.mysql.controller.WebController required a bean named ‘entityManagerFactory’ that could not be found.

    Action:

    Consider defining a bean named ‘entityManagerFactory’ in your configuration.

    1. while following this procedure

      2. Step to do
      – Create Spring Boot project & add Dependencies
      – Configure Spring JPA
      – Create DataModel Class
      – Create Spring JPA Repository Interface
      – Create Web Controller
      – Create MySQL table
      – Run Spring Boot Application & Enjoy Result

  2. I have the same problem as you… It terms out to be spring-boot-starter-parent 2.0.1 release have a build path problem with aspectjweaver… If you change it to 1.4.3 solve it. Its strange why the most updated doesn’t work.

  3. ***************************
    APPLICATION FAILED TO START
    ***************************

    Description:

    Field repository in com.Shruti.db.springmysql.controller.WebController required a bean named ‘entityManagerFactory’ that could not be found.

    Action:

    Consider defining a bean named ‘entityManagerFactory’ in your configuration.

    I have been getting this error with ur code

Got Something To Say:

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

*