Sie sind auf Seite 1von 12

7/31/2017 Spring Data JPA using Spring Boot Application | Dinesh on Java

Follow

Home Core Java Spring Spring Boot Hibernate Struts 2 J2EE Web Services Hadoop Design Patterns Maven MongoDB

Replay
*T&C apply.

Spring Data JPA using Spring Boot Application


Posted by Dinesh Rajput

*T&C apply.
Hello friends !!! In this tutorial we are going to discuss how to use and congure Spring Data JPA with Spring Boot
Applica on with minimal congura on as always with Spring Boot. Spring Data JPA and Hibernate (as JPA implementa on)
will be used to implement the data access layer.

Dinesh
20,502 like

Like Page

1 friend likes this

Google Cloud Platform.


Start your rst VM for free with Google
Compute Engine.
Google Cloud Platform

Related Tutorials

1. Introduc on to Spring Boot


2. Spring Boot Ini alizr Web Interface
3. External Congura on for Spring Boot Applica on
4. Spring MVC with Spring Boot
5. SQL Database with Spring Boot
6. MySQL Congura on with Spring Boot

Spring Data?
Spring Data is a high level project developed by Spring community aimed at simplifying the data access opera ons for the
applica ons. If you are using Spring Data in your project, you are not going to write most of the low level data access
opera ons like wri ng SQL query DAO classes etc. Spring Data will generate everything dynamically at run- me by crea ng
the proxy instances of your abstract repositories and perform the required opera ons.

There are several sub projects provided by Spring Data like Spring Data JPA, Spring Data Solr, Spring Data MongoDB, Spring
Data REST etc. Here we are going to discuss one of them Spring Data JPA.

Spring Data JPA?


The Spring Data JPA is the implementa on of JPA for simplifying opera on like data accessing, querying, pagina on and
removes lots of boilerplate codes. The Java Persistence API is a standard technology that allows you to map objects to
rela onal databases. The spring-boot-starter-data-jpa POM provides a quick way to get started. It provides the following
key dependencies: LABELS

About My Profession
AJAX (4)
HibernateOne of the most popular JPA implementa ons. Ant (11)
Spring Data JPAMakes it easy to implement JPA-based repositories. cloud computing
collection
Spring ORMsCore ORM support from the Spring Framework
Core JAVA
Core Java Interview

http://www.dineshonjava.com/2016/08/spring-data-jpa-using-in-spring-boot-application.html 1/12
7/31/2017 Spring Data JPA using Spring Boot Application | Dinesh on Java

Spring Data Repositories Follow


Garbage Collection
GitHub (3)
Spring data provides the abstract repositories, which are implemented at run- me by the spring container and perform the
Gradle (3)
CRUD opera ons. As a developer we have to just provide the abstract methods in the interface. This reduces the amount of Hadoop (14)
boilerplate code required to write data access layers. There are following are base interfaces providing by Spring Data. Hibernate
hibernate4
interview questions
Repository
Java (5)
It is the central interface in the spring data repository abstrac on. This is a marker interface. Java Code Best Prac
JavaMail (14)

CrudRepository JAXB (4)


JDBC (1)
CrudRepository provides methods for the CRUD opera ons. This interface extends the Repository interface. If you are
JSP (29)
extending the CrudRepository, there is no need for implemen ng your own methods. Just extend this interface and leave it JSTL (44)
as blank. Linux (2)
Logging (2)
maven (12)
JpaRepository
Microservices
This is the special version of CrudRepository specic to the JPA technology. Recommended to use CrudRepository because migration (1)
it will not e your applica on with any specic store implementa ons. mongodb
motivational
multithreading
PagingAndSor ngRepository
OCPJP (4)
It is specialized version for the paging opera ons and extension of CrudRepository. REST (24)
Security (1)

Spring Data JPA and Spring Boot Applica on Servlet (26)


SOAP (9)
Here I am going make at REST API applica on for providing the booking informa on of train cket and also we can the book
Spring 5 (2)
the train cket using API. Here I am using MySQL database in a Spring Boot web applica on, using less code and Spring AOP
congura ons as possible. First we have to create the project so I am using here Spring Boot Web Ini alizr for crea ng Spring Batch

project with selec ng maven build and required dependencies for this project like WEB, SPRING DATA JPA, and MYSQL. Spring Batch3
Spring Boot
Now lets see required part of the maven le for this project.
Spring HATEOAS
Spring Mobile
Spring MVC
Spring MVC interview
1. <?xml version="1.0" encoding="UTF-8"?> Spring REST

2. <project xmlns="http://maven.apache.org/POM/4.0.0" Spring3.0


Spring4 (37)
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
SpringSecurity
3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 String in Java

http://maven.apache.org/xsd/maven-4.0.0.xsd"> struts2 (49)


thymeleaf
4. <modelVersion>4.0.0</modelVersion> UDDI (1)
5. WebService
WSDL (9)
6. <groupId>com.dineshonjava.sdjpa</groupId>
7. <artifactId>SpringBootJPASpringData</artifactId>
9 1 2
8. <version>0.0.1-SNAPSHOT</version>
9. <packaging>jar</packaging> MENU
10.
2017 (74)
11. <name>SpringBootJPASpringData</name> 2016 (60)
12. <description>SpringBootJPASpringData project for Spring Boot with Spring Data JPA November

implementation</description> October (22)


September
13.
August (12)
14. <parent> July (6)

15. <groupId>org.springframework.boot</groupId> June (7)


March (8)
16. <artifactId>spring-boot-starter-parent</artifactId>
February (1)
17. <version>1.4.0.RELEASE</version> January (1)
18. <relativePath/> <!-- lookup parent from repository --> 2015 (11)
19. </parent> 2014 (89)

20. 2013 (352)


2012 (85)
21. <properties>
22. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

http://www.dineshonjava.com/2016/08/spring-data-jpa-using-in-spring-boot-application.html 2/12
7/31/2017 Spring Data JPA using Spring Boot Application | Dinesh on Java

24. <java.version>1.8</java.version> Follow


25. </properties>
26.
27. <dependencies>
28. <dependency>
29. <groupId>org.springframework.boot</groupId>
30. <artifactId>spring-boot-starter-data-jpa</artifactId>
31. </dependency>
32. <dependency>
33. <groupId>org.springframework.boot</groupId>
34. <artifactId>spring-boot-starter-web</artifactId>
35. </dependency>
36.
37. <!-- <dependency>
38. <groupId>com.h2database</groupId>
39. <artifactId>h2</artifactId>
40. <scope>runtime</scope>
41. </dependency> -->
42. <dependency>
43. <groupId>mysql</groupId>
44. <artifactId>mysql-connector-java</artifactId>
45. <scope>runtime</scope>
46. </dependency>
47. <dependency>
48. <groupId>org.springframework.boot</groupId>
49. <artifactId>spring-boot-starter-test</artifactId>
50. <scope>test</scope>
51. </dependency>
52. </dependencies>
53.
54. <build>
55. <plugins>
56. <plugin>
57. <groupId>org.springframework.boot</groupId>
58. <artifactId>spring-boot-maven-plugin</artifactId>
59. </plugin>
60. </plugins>
61. </build>
62.
63.
64. </project>

If you look at the above maven dependencies.


spring-boot-starter-data-jpa dependency will download the les required for spring data jpa.
spring-boot-starter-web is required because it is web based applica on to expose the REST endpoints.
mysql-connector-java dependency will download the les required for mysql database.

http://www.dineshonjava.com/2016/08/spring-data-jpa-using-in-spring-boot-application.html 3/12
7/31/2017 Spring Data JPA using Spring Boot Application | Dinesh on Java

Congura on le applica on.proper es Follow

1. # DataSource settings: set here your own configurations for the database
2. # connection. In this example we have "dojsb" as database name and
3. # "root" as username and password.
4. spring.datasource.url = jdbc:mysql://localhost:3307/dojdb
5. spring.datasource.username = root
6. spring.datasource.password = root
7.
8. # Keep the connection alive if idle for a long time (needed in production)
9. spring.datasource.testWhileIdle = true
10. spring.datasource.validationQuery = SELECT 1
11.
12. # Show or not log for each sql query
13. spring.jpa.show-sql = true
14.
15. # Hibernate ddl auto (create, create-drop, update)
16. spring.jpa.hibernate.ddl-auto = create
17.
18. # Naming strategy
19. spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
20.
21. # Use spring.jpa.properties.* for Hibernate native properties (the prefix is
22. # stripped before adding them to the entity manager)
23.
24. # The SQL dialect makes Hibernate generate better SQL for the chosen database
25. spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
26.
27. server.port = 8181

Using hibernate congura on ddl-auto = update the database schema will be automa cally created (and updated),
crea ng tables and columns, accordingly to java en es found in the project. For this applica on I am using server port is
8181.

En ty le Booking.java
Create an en ty class represen ng a table in your db. Here I am using Booking.java as en ty les which map to the
booking table in the database dojdb.

1. /**
2. *
3. */
4. package com.dineshonjava.sdjpa.models;
5.
6. import java.io.Serializable;
7. import java.util.Date;
8.
9. import javax.persistence.Column;
10. import javax.persistence.Entity;
http://www.dineshonjava.com/2016/08/spring-data-jpa-using-in-spring-boot-application.html 4/12
7/31/2017 Spring Data JPA using Spring Boot Application | Dinesh on Java

11. import javax.persistence.GeneratedValue; Follow


12. import javax.persistence.GenerationType;
13. import javax.persistence.Id;
14. import javax.persistence.Table;
15.
16. /**
17. * @author Dinesh.Rajput
18. *
19. */
20. @Entity
21. @Table(name = "BOOKING")
22. public class Booking implements Serializable{
23.
24. /**
25. *
26. */
27. private static final long serialVersionUID = 1L;
28. @Id
29. @GeneratedValue(strategy = GenerationType.AUTO)
30. Long bookingId;
31. @Column
32. String psngrName;
33. @Column
34. String departure;
35. @Column
36. String destination;
37. @Column
38. Date travelDate;
39.
40. public Long getBookingId() {
41. return bookingId;
42. }
43.
44. public void setBookingId(Long bookingId) {
45. this.bookingId = bookingId;
46. }
47.
48. public String getPsngrName() {
49. return psngrName;
50. }
51.
52. public void setPsngrName(String psngrName) {
53. this.psngrName = psngrName;
54. }
55.
56. public String getDeparture() {
57. return departure;
58. }
59.

http://www.dineshonjava.com/2016/08/spring-data-jpa-using-in-spring-boot-application.html 5/12
7/31/2017 Spring Data JPA using Spring Boot Application | Dinesh on Java

60. public void setDeparture(String departure) { Follow


61. this.departure = departure;
62. }
63.
64. public String getDestination() {
65. return destination;
66. }
67.
68. public void setDestination(String destination) {
69. this.destination = destination;
70. }
71.
72. public Date getTravelDate() {
73. return travelDate;
74. }
75.
76. public void setTravelDate(Date travelDate) {
77. this.travelDate = travelDate;
78. }
79.
80.
81. }

The @En ty annota on marks this class as a JPA en ty. The @Table annota on species the db tables name.

The Data Access Object (Repository): BookingRepository.java


Repository is needed to works with en es in databases table, with methods like save, delete, update, etc. With Spring
Data JPA a DAO for your en ty is simply created by extending the CrudRepository interface provided by Spring. The
following methods are some of the ones available from such interface: save, delete, deleteAll, ndOne and ndAll.

1. package com.dineshonjava.sdjpa.models;
2.
3. import org.springframework.data.repository.CrudRepository;
4. import org.springframework.transaction.annotation.Transactional;
5.
6. @Transactional
7. public interface BookingRepository extends CrudRepository {
8.
9. /**
10. * This method will find an Boooking instance in the database by its departure.
11. * Note that this method is not implemented and its working code will be
12. * automatically generated from its signature by Spring Data JPA.
13. */
14. public Booking findByDeparture(String departure);
15. }
16.

Adding Rest Controller BookingController.java

http://www.dineshonjava.com/2016/08/spring-data-jpa-using-in-spring-boot-application.html 6/12
7/31/2017 Spring Data JPA using Spring Boot Application | Dinesh on Java

Here adding one more le for accessing Rest APIs is RestController it provide me some URLs for CRUD opera onFollow
the
booking table.

1. /**
2. *
3. */
4. package com.dineshonjava.sdjpa.controller;
5.
6. import java.util.Date;
7.
8. import org.springframework.beans.factory.annotation.Autowired;
9. import org.springframework.web.bind.annotation.RequestMapping;
10. import org.springframework.web.bind.annotation.RequestParam;
11. import org.springframework.web.bind.annotation.RestController;
12.
13. import com.dineshonjava.sdjpa.models.Booking;
14. import com.dineshonjava.sdjpa.models.BookingRepository;
15.
16. /**
17. * @author Dinesh.Rajput
18. *
19. */
20. @RestController
21. @RequestMapping("/booking")
22. public class BookingController {
23.
24. @Autowired
25. BookingRepository bookingRepository;
26. /**
27. * GET /create --> Create a new booking and save it in the database.
28. */
29. @RequestMapping("/create")
30. public Booking create(Booking booking) {
31. booking.setTravelDate(new Date());
32. booking = bookingRepository.save(booking);
33. return booking;
34. }
35.
36. /**
37. * GET /read --> Read a booking by booking id from the database.
38. */
39. @RequestMapping("/read")
40. public Booking read(@RequestParam Long bookingId) {
41. Booking booking = bookingRepository.findOne(bookingId);
42. return booking;
43. }
44.
45. /**
46. * GET /update --> Update a booking record and save it in the database.
http://www.dineshonjava.com/2016/08/spring-data-jpa-using-in-spring-boot-application.html 7/12
7/31/2017 Spring Data JPA using Spring Boot Application | Dinesh on Java

47. */ Follow
48. @RequestMapping("/update")
49. public Booking update(@RequestParam Long bookingId, @RequestParam String psngrName) {
50. Booking booking = bookingRepository.findOne(bookingId);
51. booking.setPsngrName(psngrName);
52. booking = bookingRepository.save(booking);
53. return booking;
54. }
55.
56. /**
57. * GET /delete --> Delete a booking from the database.
58. */
59. @RequestMapping("/delete")
60. public String delete(@RequestParam Long bookingId) {
61. bookingRepository.delete(bookingId);
62. return "booking #"+bookingId+" deleted successfully";
63. }
64. }

Thats all! The connec on with the database is done when we run the following le as Java Applica on or Spring Boot
applica on.

1. import org.springframework.boot.SpringApplication;
2. import org.springframework.boot.autoconfigure.SpringBootApplication;
3.
4. @SpringBootApplication
5. public class SpringBootJpaSpringDataApplication {
6.
7. public static void main(String[] args) {
8. SpringApplication.run(SpringBootJpaSpringDataApplication.class, args);
9. }
10. }

Project Structure:

http://www.dineshonjava.com/2016/08/spring-data-jpa-using-in-spring-boot-application.html 8/12
7/31/2017 Spring Data JPA using Spring Boot Application | Dinesh on Java

Follow

Test the controller launching the Spring Boot web applica on and using these urls:

Crea ng New Record:


/booking/create?psngrName=Dinesh&departure=Noida&des na on=Pune create a new booking with an auto-generated.
For Example:
h p://localhost:8181/booking/create?psngrName=Arnav&des na on=USA&departure=Delhi
{
bookingId: 4,
psngrName: "Arnav",
departure: "Delhi",
des na on: "USA",
travelDate: 1470828738680
}

Reading a Record:
/booking/read?bookingId=[bookingId]: Read the booking with the passed bookingId.

For Example:
h p://localhost:8181/booking/read?bookingId=1

{
bookingId: 1,
psngrName: "Dinesh",
departure: "Noida",
des na on: "Pune",
travelDate: 1470828563000
}
Upda ng a Record:
/booking/update?bookingId=[bookingId]&psngrName=Sweety: Update the booking for a given booking id.

For Example:
h p://localhost:8181/booking/update?bookingId=5&psngrName=Suresh
{
bookingId: 5,
psngrName: "Suresh",
departure: "Agra",
des na on: "Noida",
travelDate: 1470828994000
}
Dele ng a Record:

http://www.dineshonjava.com/2016/08/spring-data-jpa-using-in-spring-boot-application.html 9/12
7/31/2017 Spring Data JPA using Spring Boot Application | Dinesh on Java

/booking/delete? bookingId=[bookingId]: Delete a booking for given booking id. Follow

For Example:
h p://localhost:8181/booking/delete?bookingId=5
booking #5 deleted successfully

For Whole Code of this applica on

h ps://github.com/DOJ-So wareConsultant/SpringBootJPASpringData

Summary
In this chapter I have explained how to use Spring Data JPA and Spring Boot frameworks. Also explained in short about the
Spring Data Repositories and query methods.

Happy Spring Boot Learning!!!

Spring Boot Related Topics


1. Spring Boot Interview Ques ons and Answers
2. Introduc on to Spring Boot
3. Essen als and Key Components of Spring Boot
4. Spring Boot CLI Installa on and Hello World Example
5. Spring Boot Ini alizr Web Interface
6. Spring Boot Ini alizr With IDEs
7. Spring Boot Ini alizr With Spring Boot CLI
8. Installing Spring Boot
9. Developing your rst Spring Boot applica on
10. External Congura ons for Spring Boot Applica ons
11. Logging Congura on in Spring Boot
12. Spring Boot and Spring MVC
13. Working with SQL Databases and Spring Boot
14. MySQL Congura ons
15. Spring Boot with NoSQL technologies
16. Spring Cache Tutorial
17. Spring Security Tutorial with Spring Boot
18. Spring Boot and MongoDB in REST Applica on
19. Complete Guide for Spring Boot Actuator
20. Microservices with Spring Boot

http://www.dineshonjava.com/2016/08/spring-data-jpa-using-in-spring-boot-application.html 10/12
7/31/2017 Spring Data JPA using Spring Boot Application | Dinesh on Java

5 Comments dineshonjava
1 Login
Follow

Sort by Best
Recommend 4 Share

Join the discussion

LOG IN WITH

OR SIGN UP WITH DISQUS ?

Name

Lenadro 4 months ago


Hello, nice tutorial. Thanks
I have a question. What I should consider when using h2 DB? It is the same?
Reply Share

Dinesh Rajput Mod > Lenadro 4 months ago

Hello, thanks for commenting.


Please have a look into this tutorial link. This has your answer.
http://www.dineshonjava.com...
Reply Share

Huang Binfang 5 months ago


when I run it, I got the error:
UnsatisfiedDependencyException: Error creating bean with name 'bookingController': Unsatisfied dependency expressed
through field 'bookingRepository';

Caused by: java.lang.IllegalArgumentException: Not a managed type: class java.lang.Object


Reply Share

Huang Binfang > Huang Binfang 5 months ago


the issue has been fixed by change the repository to :

import org.springframework.data.repository.CrudRepository;

import javax.transaction.Transactional;

@Transactional
public interface BookingRepository extends CrudRepository<booking, long=""> {

Thanks.
Reply Share

Dinesh Rajput Mod > Huang Binfang 5 months ago

Yes, It is good.
Thanks
Reply Share

ALSO ON DINESHONJAVA

Method injection with Spring using Lookup method Spring Boot Actuator A Complete Guide
property 5 comments a year ago
2 comments 6 months ago Dinesh Rajput Thanks Mohan for your view.
Dinesh Rajput Thanks Naved.

RequestMapping Annotation in Spring MVC | DOJ How to find all Pairs in Array of Integers whose Sum is
Software Consultant equal to a given Number
2 comments a year ago 2 comments 7 months ago
Dinesh Rajput Thanks for your feedback. Dinesh Rajput Could you please suggest best solution if you
have!
Newer Post Home Older Post

http://www.dineshonjava.com/2016/08/spring-data-jpa-using-in-spring-boot-application.html 11/12
7/31/2017 Spring Data JPA using Spring Boot Application | Dinesh on Java
POPULAR POSTS
Follow

Spring MVC Hibernate Integration CRUD Example Step by Step


In this example show how to write a simple web based application with CRUD operation using Spring3 MVC Framwork with Hibernate3 using Annot...

Core Java Tutorial-Learn Step by Step with Example


Hello Friends, Now we will focused on the Core Java tutorial, it is really a baby step to be a good, better and best Java ian :-) . I mea...

Spring Tutorial- Learn Framework Overview Step by Step


In this series of spring tutorial, its provides many step by step examples and explanations on using Spring framework. The Spring framewor...

Spring Security Tutorial- Learn Step to Secure Web


In this spring security tutorial we will discuss about some of the security tips about the Spring Framework. Spring Security is a powerful...

How does java Hashmap work internally


What is Hashing? Hashing in its simplest form, is a way to assigning a unique code for any variable/object after applying any formula/algor...

REST and SOAP Web Service Interview Questions


In this interview questions tutorial we will explain most asking interviews questions on the web services like SOAP, REST etc and its protoc...

Spring Boot Tutorial Best Complete Introduction


Hello friends today I am going to discuss one of the latest innovation by the Spring Team (Pivotal Team) is Spring Boot, oops... sorry..fri...

Learn to Spring MVC Framework Tutorial with Simple Example


Model view controller is a software architecture design pattern. It provides solution to layer an application by separating three concerns...

NamedParameterJdbcTemplate in Spring with Example


The NamedParameterJdbcTemplate class helps you specify the named parameters inste a d of classic placeholder('?') argument. Named pa...

Spring Batch Tutorial - Introduction Get Best Examples


Hi In this spring batch tutorial I will discuss about one of the excellent feature of Spring Framework name Spring Batch. Spring Batch is a ...

http://www.dineshonjava.com/2016/08/spring-data-jpa-using-in-spring-boot-application.html 12/12

Das könnte Ihnen auch gefallen