Restful Crud API
Restful Crud API
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
1 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
Spring Boot provides a web tool called Spring Initializer to bootstrap an application
quickly. Just go to http://start.spring.io and follow the steps below to generate a new
project.
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
2 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
Once all the details are entered, click Generate Project to generate and download
your project. Spring Initializer will generate the project with the 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.
3 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
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.SpringBootApplication;
@SpringBootApplication
public class EasyNotesApplication {
4 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
2. resources/
This directory, as the name suggests, is dedicated to all the static resources, templates
and property �les.
5 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
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 chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
6 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
spring.jpa.hibernate.ddl-auto = update
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.
When you de�ne a domain model, a table will automatically be created in the
database and the �elds of the domain model will be mapped to the corresponding
columns in the table.
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 -
7 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
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.AuditingEntityListener;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import java.util.Date;
@Entity
@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;
8 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date updatedAt;
All your domain models must be annotated with @Entity annotation. It is used
to mark the class as a persistent Java class.
@Table annotation is used to provide the details of the table that this entity will
be mapped to.
@NotBlank annotation is used to validate that the annotated �eld is not null
or empty.
@Column annotation is used to de�ne the properties of the column that will be
mapped to the annotated �eld. You can de�ne several properties like name,
length, nullable, updateable etc.
9 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
If you want to map the �eld to a di�erent column, you can specify it using -
@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.
In our Note model we have annotated createdAt and updatedAt �elds with
@CreatedDate and @LastModifiedDate annotations respectively.
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) .
10 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
package com.example.easynotes;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
@SpringBootApplication
@EnableJpaAuditing
public class EasyNotesApplication {
The next thing we’re gonna do is create a repository to access Note’s data from the
database.
11 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
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> {
Note that, we have annotated the interface with @Repository annotation. This tells
Spring to bootstrap the repository during component scan.
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.
Spring Data JPA has a bunch of other interesting features like Query methods
(dynamically creating queries based on method names), Criteria API, Speci�cations,
QueryDsl etc.
12 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
I strongly recommend you to checkout the Spring Data JPA’s documentation to learn
more.
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 String resourceName;
private String fieldName;
private Object fieldValue;
13 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
return resourceName;
}
Notice the use of @ResponseStatus annotation in the above exception class. This will
cause Spring boot to respond with the speci�ed HTTP status code whenever this
exception is thrown from your controller.
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.*;
14 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
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.
15 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
The @RequestBody annotation is used to bind the request body with a method
parameter.
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.
16 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
@GetMapping("/notes/{id}")
public Note getNoteById(@PathVariable(value = "id") Long noteId) {
return noteRepository.findById(noteId)
.orElseThrow(() -> new ResourceNotFoundException("Note", "id", noteId
}
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 noteDetails)
note.setTitle(noteDetails.getTitle());
note.setContent(noteDetails.getContent());
17 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
// Delete a Note
@DeleteMapping("/notes/{id}")
public ResponseEntity<?> deleteNote(@PathVariable(value = "id") Long noteId)
Note note = noteRepository.findById(noteId)
.orElseThrow(() -> new ResourceNotFoundException("Note", "id", noteId
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
The application will start at Spring Boot’s default tomcat port 8080.
18 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
19 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
20 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
More Resources
The application that we built in this article had only one domain model. If you want to
learn how to build REST APIs in an application with more than one domain models
exhibiting a one-to-many relationship between each other, then I highly recommend
you to check out the following article -
Also, Go through the following article to learn how to build a full stack application with
authentication and authorization using Spring Boot, Spring Security and React -
Spring Boot + Spring Security + JWT + MySQL + React Full Stack Polling App - Part 1
Conclusion
Congratulations folks! We successfully built a Restful CRUD API using Spring Boot,
Mysql, Jpa and Hibernate.
You can �nd the source code for this tutorial on my github repository. Feel free to
clone the repository and build upon it.
21 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
Thank you for reading. Please ask any questions in the comment section below.
22 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
Name
<dependency>
<groupid>com.microsoft.sqlserver</groupid>
<artifactid>mssql-jdbc</artifactid>
<version>6.1.0.jre8</version>
<scope>runtime</scope>
</dependency>
23 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
24 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
CalliCoder
Software Development Tutorials written from the heart!
Copyright © 2017-2018
ABOUT
25 de 26 08/02/19 21:58
Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutori... https://www.callicoder.com/spring-boot-rest-api-tutorial-with-...
About CalliCoder
Advertise
Contact Us
Privacy Policy
Sitemap
RESOURCES
Recommended Books
Recommended Courses
URL Encoder
URL Decoder
ASCII Table
CONNECT
Github
Google+
26 de 26 08/02/19 21:58