Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial - CalliCoder
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial - CalliCoder
Spring Boot has taken Spring framework to the next level. It has drastically
reduced the con guration and setup time required for spring projects.
You can setup a project with almost zero con guration and start building the
things that actually matter to your application.
If you are new to Spring boot and want to get started with it quickly, then this
blog post is for you.
In this post, we’ll build a Restful CRUD API for a simple note-taking application.
A Note can have a title and some content. We’ll rst build the apis to create,
retrieve, update and delete a Note, and then test them using postman.
C ALLIC ODE R
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 1/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
Group : com.example
Artifact : easy-notes
Name : easy-notes
Description : Rest API for a Simple Note Taking Application
Package Name : com.example.easynotes
Packaging : jar (This is the default value)
Java Version : 1.8 (Default)
Dependencies : Web, JPA, MySQL, DevTools
Once all the details are entered, click Generate Project to generate and
C ALLIC ODE R
download your project. Spring Initializer will generate the project with the
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 2/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
details you have entered and download a zip le with all the project folders.
Next, Unzip the downloaded zip le and import it into your favorite IDE.
Let’s understand the details of some of the important les and directories -
1. EasyNotesApplication
package com.example.easynotes;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplicati
C ALLIC ODE R
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 3/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
@SpringBootApplication
public class EasyNotesApplication {
2. resources/
This directory, as the name suggests, is dedicated to all the static resources,
templates and property les.
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 4/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
You can refer this page for common application properties used in Spring
Boot.
So, we just have to add the con guration and Spring Boot will take care of the
rest.
## Hibernate Properties
# The SQL dialect makes Hibernate generate better SQL for the cho
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.M
C ALLIC ODE R
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 5/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
You will need to create a database named notes_app in MySQL, and change
the spring.datasource.username & spring.datasource.password
properties as per your MySQL installation.
In the above properties le, the last two properties are for hibernate. Spring
Boot uses Hibernate as the default JPA implementation.
Any change to the domain model will also trigger an update to the table.
For example, If you change the name or type of a eld, or add another
eld to the model, then all these changes will be re ected in the mapped
table as well.
All right! Let’s now create the Note model. Our Note model has following
elds -
Now, let’s see how we can model this in Spring. Create a new package called
model inside com.example.easynotes and add a class named Note.java
with following contents -
package com.example.easynotes.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntity
import javax.persistence.*; Search CalliCoder
import javax.validation.constraints.NotBlank;
Java java.util.Date;
import Kotlin Golang Spring Boot Node.js JavaFX
@Entity
About
@Table(name = "notes")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
allowGetters = true)
public class Note implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
private String title;
@NotBlank
private String content;
C ALLIC ODE R
@Column(nullable = false, updatable = false)
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 7/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdAt;
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date updatedAt;
@Table annotation is used to provide the details of the table that this
entity will be mapped to.
IfCyou want to map the eld to a di erent column, you can specify it using -
ALLIC ODE R
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 8/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
@Column(name = "created_on")
private String createdAt;
This annotation is used because we don’t want the clients of the rest api to
supply the createdAt and updatedAt values. If they supply these
values then we’ll simply ignore them. However, we’ll include these values
in the JSON response.
Now, what we want is that these elds should automatically get populated
whenever we create or update an entity.
We have already done this in our Note model with the annotation
@EntityListeners(AuditingEntityListener.class) .
C ALLIC ODE R
@SpringBootApplication
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 9/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
@EnableJpaAuditing
public class EasyNotesApplication {
The next thing we’re gonna do is create a repository to access Note’s data
from the database.
Well, Spring Data JPA has got us covered here. It comes with a
JpaRepository interface which de nes methods for all the CRUD
operations on the entity, and a default implementation of JpaRepository
called SimpleJpaRepository .
Cool! Let’s create the repository now. First, Create a new package called
repository inside the base package com.example.easynotes . Then,
create an interface called NoteRepository and extend it from
JpaRepository -
package com.example.easynotes.repository;
import com.example.easynotes.model.Note;
import org.springframework.data.jpa.repository.JpaRepository;
@Repository
public interface NoteRepository extends JpaRepository<Note, Long>
C ALLIC ODE R
}
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 10/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
Great! That is all you have to do in the repository layer. You will now be able to
use JpaRepository’s methods like save() , findOne() , findAll() ,
count() , delete() etc.
You don’t need to implement these methods. They are already implemented
by Spring Data JPA’s SimpleJpaRepository . This implementation is plugged
in by Spring automatically at runtime.
We’ll de ne the Rest APIs for creating, retrieving, updating, and deleting a
Note in the next section.
package com.example.easynotes.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
private
C ALLIC ODE RString resourceName;
private String fieldName;
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 11/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
Creating NoteController
The Final Step - We’ll now create the REST APIs for creating, retrieving,
updating and deleting a Note.
package com.example.easynotes.controller;
import com.example.easynotes.exception.ResourceNotFoundException;
import com.example.easynotes.model.Note;
import com.example.easynotes.repository.NoteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/api")
public class NoteController {
@Autowired
NoteRepository noteRepository;
// Update a Note
// Delete a Note
}
@RequestMapping("/api") declares that the url for all the apis in this
controller will start with /api .
Let’s now look at the implementation of all the apis one by one.
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 14/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
The @Valid annotation makes sure that the request body is valid.
Remember, we had marked Note’s title and content with @NotBlank
annotation in the Note model?
If the request body doesn’t have a title or a content, then spring will return a
400 BadRequest error to the client.
This will cause Spring Boot to return a 404 Not Found error to the client
(Remember, we had added a @ResponseStatus(value =
HttpStatus.NOT_FOUND) annotation to the ResourceNotFoundException
class).
// Update a Note
@PutMapping("/notes/{id}")
public Note updateNote(@PathVariable(value = "id") Long noteId,
@Valid @RequestBody Note
C ALLIC ODE R
Note note = noteRepository.findById(noteId)
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 15/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
note.setTitle(noteDetails.getTitle());
note.setContent(noteDetails.getContent());
// Delete a Note
@DeleteMapping("/notes/{id}")
public ResponseEntity<?> deleteNote(@PathVariable(value = "id") L
Note note = noteRepository.findById(noteId)
.orElseThrow(() -> new ResourceNotFoundException("Not
noteRepository.delete(note);
return ResponseEntity.ok().build();
}
We’ve successfully built all the apis for our application. Let’s now run the app
and test the apis.
Just go to the root directory of the application and type the following
command to run it -
$ mvn spring-boot:run
C ALLIC ODE R
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 16/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
The application will start at Spring Boot’s default tomcat port 8080.
C ALLIC ODE R
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 17/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
C ALLIC ODE R
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 18/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
Conclusion
You can nd the source code for this tutorial on my github repository. Feel
free to clone the repository and build upon it.
Thank you for reading. Please ask any questions in the comment section
below.
68 Comments CalliCoder
1 Login
Sort by Best
Recommend 11 ⤤ Share
LOG IN WITH
OR SIGN UP WITH DISQUS ?
Name
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 20/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
Some of the fields in the Note model might be null while saving. I guess createdAt
and updatedAt fields are not being set. Please make sure that you're adding
@EnableJpaAuditing annotation in the main class and
@EntityListeners(AuditingEntityListener.class) annotation in the Note model.
You can also check the complete source code on github and verify everything.
△ ▽ • Reply • Share ›
Rajeev, can i get any example where i find how to call typescript through
rest API, which is developed on spring boot and jpa.
△ ▽ • Reply • Share ›
I am facing this issue and tried to debug it but I couldn't end up with a successful
conclusion. Please help!
1△ ▽ • Reply • Share ›
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@UpdateTimestamp
private Date updatedAt;
△ ▽ • Reply • Share ›
Error says that the value for created_at field is empty. Please make sure that
you're adding @EnableJpaAuditing annotation in the main class and
@EntityListeners(AuditingEntityListener.class) annotation in the Note model.
△ ▽ • Reply • Share ›
Hi Pruthvi,
Can you create a Pull Request in this github repo with your code? It
will be easier to debug from there.
Cheers,
Rajeev
△ ▽ • Reply • Share ›
Hi Pruthvi,
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 22/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
Rajeev Kumar Singh Mod > Osman Otoniel Mazariegos Mende • 9 hours ago
Hi,
Honestly, It's very difficult to know the exact reason for the error just by that
message. Please post the full stacktrace if the error is coming even if the above
things are fine.
Cheers!
Rajeev
△ ▽ • Reply • Share ›
Hi,
The error says that It could not find NoteRepository dependency during component
scan.
Please verify that you have created the NoteRepository interface inside
com.example.easynotes.repository package as described in the article. Also,
Please make sure that the @Repository annotation is added to it.
△ ▽ • Reply • Share ›
C ALLIC ODE R Manjunath Gundra > Rajeev Kumar Singh • 21 days ago
Rajeev - I did.. please find the same in the below screenshot
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 24/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
△ ▽ • Reply • Share ›
This looks good. Not sure what else can go wrong. It would be great
if you can you create a pull request with your code on the Github
Repository. I'll quickly check it out.
△ ▽ • Reply • Share ›
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 25/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
Error creating bean with name 'noteRepository': Cannot create inner bean '(inner
bean)#19f9d595' 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)#19f9d595': Cannot resolve reference to bean 'entityManagerFactory'
while setting constructor argument; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named
'entityManagerFactory' available
△ ▽ • Reply • Share ›
Hey Richa, Please make sure that you have created a database named notes_app
in MySQL, and changed the spring.datasource.username &
spring.datasource.password properties as per your MySQL installation.
△ ▽ • Reply • Share ›
headers might have been stored from any request to a different service.
△ ▽ • Reply • Share ›
ue.
5△ ▽ • Reply • Share ›
{
"timestamp": "2018-01-31T10:23:15.863+0000",
"status": 400,
"error": "Bad Request",
"errors": [
{
"codes": [
"NotBlank.note.content",
"NotBlank.content",
C ALLIC ODE R
"NotBlank"
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 27/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
see more
△ ▽ • Reply • Share ›
Hi Manoj, You need to pass the title and content fields in the body of the request
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 28/28