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

123 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

  4. I like the valuable info you provide in your articles.
    I will bookmark your blog and check again right here frequently.
    I am slightly certain I’ll learn a lot of new stuff right here!
    Best of luck for the following!

  5. It is appropriate time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or suggestions. Maybe you could write next articles referring to this article. I wish to read even more things about it!

  6. I’m really impressed with your writing skills
    and also with the layout on your blog. Is this a paid theme
    or did you customize it yourself? Anyway keep up the excellent quality writing, it’s rare
    to see a nice blog like this one these days.

  7. I think that is among the so much vital info for me.

    And i’m happy studying your article. However wanna remark on some
    normal things, The site style is perfect, the articles is in reality
    great : D. Just right task, cheers

  8. Heya i’m for the first time here. I found this board and I to find It really helpful & it helped me out a
    lot. I’m hoping to give one thing again and help others such as you helped me.

  9. I’m not sure exactly why but this website is loading very
    slow for me. Is anyone else having this problem or is it a issue
    on my end? I’ll check back later and see if the problem still
    exists.

  10. I was recommended this web site by my cousin. I’m not sure whether this post is written by
    him as no one else know such detailed about my
    difficulty. You are incredible! Thanks!

  11. Thank you, I’ve recently been looking for info approximately this subject for
    ages and yours is the best I’ve came upon till now.

    But, what concerning the conclusion? Are you sure about the source?

  12. Simply wish to say your article is as surprising. The clarity in your post is just excellent and i could suppose you’re a professional on this subject. Well along with your permission allow me to seize your feed to stay up to date with coming near near post. Thanks a million and please continue the enjoyable work.|

  13. Please let me know if you’re looking for a author for your weblog. You have some really great articles and I believe I would be a good asset. If you ever want to take some of the load off, I’d absolutely love to write some material for your blog in exchange for a link back to mine. Please send me an e-mail if interested. Cheers!|

  14. Normally I don’t read article on blogs, however I wish to say that this write-up very forced me to try and do so! Your writing taste has been amazed me. Thank you, quite nice article.

  15. I like this post, enjoyed this one regards for posting. “‘I have done my best.’ That is about all the philosophy of living one needs.” by Lin Yutang.

  16. Hey very nice blog!! Guy .. Beautiful .. Amazing .. I will bookmark your web site and take the feeds also…I am glad to seek out so many useful information right here in the post, we need develop extra techniques on this regard, thanks for sharing.

  17. Rattling excellent info can be found on site . “The greatest mistake is trying to be more agreeable than you can be.” by Walter Bagehot.

  18. Hello, Neat post. There is a problem with your website in web explorer, may check this… IE still is the marketplace leader and a large part of people will omit your excellent writing because of this problem.

  19. Thank you for the sensible critique. Me & my neighbor were just preparing to do some research about this. We got a grab a book from our local library but I think I learned more clear from this post. I am very glad to see such excellent information being shared freely out there.

  20. I just couldn’t depart your web site prior to suggesting that I actually loved the standard information an individual supply to your visitors? Is going to be again steadily in order to inspect new posts.

  21. Only wanna input on few general things, The website layout is perfect, the written content is very wonderful. “We can only learn to love by loving.” by Iris Murdoch.

  22. I have not checked in here for some time because I thought it was getting boring, but the last few posts are good quality so I guess I will add you back to my daily bloglist. You deserve it my friend 🙂

  23. you’re in point of fact a good webmaster. The website loading pace is amazing. It sort of feels that you’re doing any unique trick. Furthermore, The contents are masterpiece. you have done a fantastic activity in this subject!

  24. I simply could not go away your site before suggesting that I extremely enjoyed the standard info a person supply on your guests? Is going to be back continuously to check up on new posts.

  25. I have read several good stuff here. Definitely value bookmarking for revisiting. I wonder how a lot attempt you set to make any such magnificent informative site.

  26. Normally I don’t read article on blogs, however I wish to say that this write-up very compelled me to check out and do it! Your writing style has been amazed me. Thanks, quite nice article.

  27. Howdy very cool blog!! Guy .. Excellent .. Wonderful .. I will bookmark your site and take the feeds also…I’m glad to seek out numerous helpful info here in the publish, we need develop more strategies in this regard, thank you for sharing.

  28. I got what you mean , thankyou for putting up.Woh I am happy to find this website through google. “Money is the most egalitarian force in society. It confers power on whoever holds it.” by Roger Starr.

  29. Hey very cool website!! Man .. Beautiful .. Wonderful .. I’ll bookmark your blog and take the feeds additionally…I’m satisfied to find so many helpful information right here in the publish, we want work out extra techniques in this regard, thank you for sharing.

  30. Thank you, I’ve just been searching for info approximately this subject for ages and yours is the greatest I have discovered till now. However, what concerning the conclusion? Are you positive concerning the source?

  31. Great – I should certainly pronounce, impressed with your site. I had no trouble navigating through all the tabs and related info ended up being truly easy to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, website theme . a tones way for your client to communicate. Nice task.

  32. I have recently started a blog, the info you provide on this web site has helped me tremendously. Thank you for all of your time & work. “A creative man is motivated by the desire to achieve, not by the desire to beat others.” by Ayn Rand.

  33. I really enjoy examining on this web site, it has got fantastic content. “One should die proudly when it is no longer possible to live proudly.” by Friedrich Wilhelm Nietzsche.

  34. I have not checked in here for a while as I thought it was getting boring, but the last few posts are good quality so I guess I’ll add you back to my daily bloglist. You deserve it my friend 🙂

  35. Thank you 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 clear from this post. I am very glad to see such magnificent information being shared freely out there.

  36. Its fantastic as your other articles : D, regards for putting up. “Experience is that marvelous thing that enables you to recognize a mistake when you make it again.” by Franklin P. Jones.

  37. I do consider all of the ideas you have offered in your post. They’re very convincing and can certainly work. Still, the posts are very quick for beginners. Could you please prolong them a bit from next time? Thanks for the post.

  38. certainly like your website but you have to check the spelling on several of your posts. Several of them are rife with spelling problems and I in finding it very bothersome to inform the reality then again I’ll certainly come again again.

  39. We’re a group of volunteers and starting a new scheme in our community.
    Your site offered us with valuable info to work on. You’ve done a formidable job and our whole community will be grateful to you.

  40. I know this if off topic but I’m looking into starting my own weblog and was wondering what all is needed to get set up?
    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very internet savvy so I’m not 100% certain. Any suggestions
    or advice would be greatly appreciated. Many thanks

  41. When I originally left a comment I seem to have clicked on the -Notify me when new comments are added- checkbox and now every time a comment is
    added I receive four emails with the exact same comment.
    Perhaps there is an easy method you are able to remove me from that service?

    Thanks!

  42. Awesome blog! Is your theme custom made or did you download it from somewhere?

    A design like yours with a few simple adjustements would really make
    my blog stand out. Please let me know where
    you got your theme. Bless you

  43. I’m curious to find out what blog system you’re working
    with? I’m having some minor security problems with
    my latest blog and I’d like to find something more risk-free.
    Do you have any solutions?

  44. دی نت به عنوان یکی از قدیمی‌ترین وارد کنندگان لوازم جانبی کامپیوتر و موبایل و شبکه، با سابقه
    ترین پخش کننده عمده لوازم جانبی کامپیوتر، لپ تاپ، موبایل و تجهیزات
    شبکه در ایران – تهران با راه اندازی فروشگاه های اینترنتی جهت فروش و توزیع و پخش مسقیم لوازم جانبی کامپیوتر
    – لپ تاپ و موبایل – تبلت و تجهیزات شبکه با بیش
    از یک دهه تجربه، با پایبندی به سه اصل کلیدی،
    پرداخت در محل، ۷ روز ضمانت بازگشت کالا
    و تضمین اصل‌بودن کالا، موفق شده تا همگام با فروشگاه‌های معتبر جهان، به بزرگ‌ترین فروشگاه اینترنتی ایران تبدیل شود.
    به محض ورود به دی نت با یک سایت پر از
    کالا رو به رو می‌شوید! هر آنچه که نیاز دارید و به ذهن شما خطور می‌کند در اینجا پیدا خواهید کرد

    فروشگاه اینترنتی دی نت؛ مرکز
    پخش عمده لوازم جانبی کامپیوتر – لپ
    تاپ و موبایل – تبلت تهران.

  45. I’m really enjoying the design and layout of your website.
    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?

    Outstanding work!

  46. My brother recommended I might like this web site. He was totally right.
    This post actually made my day. You can not imagine simply how much time I had spent for this information! Thanks!

  47. We’re a group of volunteers and opening a
    new scheme in our community. Your site offered us with valuable information to work on. You’ve done an impressive job and our entire community will be thankful to you.

  48. Hey there this is somewhat of off topic but I was wanting to know if blogs use WYSIWYG editors or if you
    have to manually code with HTML. I’m starting a blog soon but have no
    coding knowledge so I wanted to get guidance from someone with experience.
    Any help would be enormously appreciated!

  49. Do you mind if I quote a few of your articles as long as I provide credit and sources back to your site?
    My blog site is in the exact same niche as yours
    and my users would definitely benefit from a lot of the information you present here.
    Please let me know if this alright with you. Regards!

  50. Hi there, I believe your site may be having browser compatibility issues.
    Whenever I take a look at your blog in Safari, it looks fine however when opening in I.E.,
    it’s got some overlapping issues. I just wanted to provide you with a quick heads up!
    Aside from that, great website!

  51. I know this if off topic but I’m looking into starting my own blog
    and was wondering what all is required to get
    setup? I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very internet smart so I’m not 100% certain. Any tips
    or advice would be greatly appreciated. Thank you

  52. Hello this is kinda of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding expertise so I wanted to get advice from someone with experience.
    Any help would be enormously appreciated!

  53. After going over a handful of the articles on your site,
    I honestly appreciate your way of writing a blog. I bookmarked it to my bookmark website list
    and will be checking back soon. Please check out my website
    as well and tell me what you think.

  54. This is really interesting, You’re a very skilled blogger.
    I’ve joined your feed and look forward to seeking more of your excellent post.
    Also, I have shared your website in my social networks!

  55. I’m really impressed with your writing skills as
    well as with the layout on your blog. Is this a paid theme
    or did you customize it yourself? Anyway keep up the excellent quality writing, it’s rare to see a great blog like this
    one today.

  56. I’m not that much of a online reader to be honest but your sites really
    nice, keep it up! I’ll go ahead and bookmark your site to come
    back later. All the best

  57. What i don’t realize is in fact how you’re not actually a lot more well-appreciated than you may be right now. You’re so intelligent. You realize thus considerably relating to this subject, made me individually imagine it from a lot of various angles. Its like women and men don’t seem to be involved except it’s something to accomplish with Lady gaga! Your own stuffs outstanding. All the time handle it up!

  58. I really enjoy reading on this website, it contains great blog posts. “One should die proudly when it is no longer possible to live proudly.” by Friedrich Wilhelm Nietzsche.

  59. Admiring the commitment you put into your site and in depth information you
    offer. It’s awesome to come across a blog every once in a while that isn’t the same outdated rehashed material.
    Great read! I’ve saved your site and I’m adding your RSS feeds to my Google account.

  60. I have read so many articles or reviews about the
    blogger lovers however this article is really a pleasant paragraph,
    keep it up.
    Esthetic Dental Clinic – DENTYSTA Toruń – Stomatologia estetyczna –
    Implanty – ORTODONTA TORUŃ
    Heleny Piskorskiej 15, 87-100 Toruń
    2MG9+W8 Toruń
    edclinic.pl

  61. Hi, I do think your blog could be having web browser compatibility issues.
    Whenever I look at your website in Safari, it looks fine however when opening in IE, it’s got some overlapping issues.
    I simply wanted to give you a quick heads up! Other than that, great site!

Leave a Reply

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