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

2. Configure Spring JPA

Open application.properties

3. Create DataModel Class

Under package model, create class Customer.

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.

5. Create Web Controller

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

Content of WebController.java

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

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

6. Create MySQL table

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 June 21, 2018.



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 *

*