Spring Data JPA is one of the module of Spring Data umbrella framework. In this tutorial we will be using it along with Spring Data REST for creating a Save operations on a MySQL database. The other Spring Data modules which we are not going to cover here are: Spring-Data-Redis, Spring-Data-Mongo, etc..
Why to use Spring Data JPA instead of Hibernate?
This is not an alternative to Hibernate, rather we use it in tandem with Hibernate or any other ORM framework.
Benefit of Spring Data JPA ?
It reduces a lot of boiler plate code of a traditional DAO layer. A developer’s job should be to concentrate more on the business logic rather than getting involved with technical complexity and boiler plate code. So basically there are 3 reasons of using Spring Data JPA:
- No-code repository.
- No boiler plate code.
- Generated queries.
Some points to remember:
- Spring Data JPA is not an implementation of JPA.
- Spring Data JPA is an Add-on to JPA.
- Spring Data JPA brings in a concept called- repositories. Which is a set of interfaces which define query methods. This acts as a DAO abstraction layer.
So, lets start….
We will be using Spring Boot for this.
Lets create a spring boot application either by spring initializr or by using below wizard in eclipse:
Lets give it a name: SpringDataJPAMySQL
Choose respective dependencies:
Hit Finish.
Finally you would be seeing below maven dependencies in your project:
<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.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
Please note that we had not added spring-boot-starter-data-rest dependency, but still we will be calling this application by a REST call.
Lets have our classes.
In application.properties add the below entires for MySQL:
## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.url = jdbc:mysql://localhost:3306/heapsteep?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false spring.datasource.username = root spring.datasource.password = root ## Hibernate Properties # The SQL dialect makes Hibernate generate better SQL for the chosen database spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect # Hibernate ddl auto (create, create-drop, validate, update) spring.jpa.hibernate.ddl-auto = update
Book.java:
package com.heapsteep.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; import lombok.Getter; import lombok.Setter; @Data @Setter @Getter @Entity @Table(name = "books") public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private int isbn; private String name; }
BookRepository.java:
package com.heapsteep.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.heapsteep.model.Book; @Repository public interface BookRepository extends JpaRepository<Book, Long>{ }
BookController.java:
package com.heapsteep.controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.heapsteep.model.Book; import com.heapsteep.repository.BookRepository; @RestController @RequestMapping("/api") public class BookController { @Autowired BookRepository bookRepository; @GetMapping("/books") public List<Book> getAllNotes() { return bookRepository.findAll(); } @PostMapping("/books") public Book createNote(@Valid @RequestBody Book book) { return bookRepository.save(book); } }
SpringDataJpaMySqlApplication.java:
package com.heapsteep; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; @SpringBootApplication public class SpringDataJpaMySqlApplication { public static void main(String[] args) { SpringApplication.run(SpringDataJpaMySqlApplication.class, args); } }
Thats it…
Right click on the SpringDataJpaMySqlApplication.java file and run as Java application.
Open a REST client (Postman/SOAPUI) and call below URL with below json input parameters:
http://localhost:8080/api/books
{ "isbn" : 123, "name" : "Book name 1" }
[P.S.] When copying the above json code, first copy it to a Notepad++ file and check the double quotes format. Otherwise you may get error: JSON parse error: Invalid UTF-8…
You will get below response:
{ "id": 1, "isbn": 123, "name": "Book name 1" }
Below is the full screenshot of the SOAPUI tool:
You can login to MySQL and see the table – books is been created and 1 record is being inserted into it.
GitHub URL for the above code:
https://github.com/heapsteep/springboot-jpa-mysql.git