You are on page 1of 28

26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder

Spring Boot, MySQL, JPA, Hibernate


Restful CRUD API Tutorial
Rajeev Kumar Singh • Spring Boot • Jul 3, 2017 • 12 mins read

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.

So, Let’s get started!

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

Creating the Project

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.

Step 1 : Click Switch to full version on http://start.spring.io page.

Step 2 : Enter the details as follows -

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.

Exploring the Directory Structure

Following is the directory structure of our Note taking application -

Let’s understand the details of some of the important les and directories -

1. EasyNotesApplication

This is the main entry point of our Spring Boot application.

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 {

public static void main(String[] args) {


SpringApplication.run(EasyNotesApplication.class, args);
}
}

It contains a simple annotation called @SpringBootApplication which is a


combination of the following more speci c spring annotations -

@Con guration : Any class annotated with @Configuration annotation


is bootstrapped by Spring and is also considered as a source of other bean
de nitions.

@EnableAutoCon guration : This annotation tells Spring to automatically


con gure your application based on the dependencies that you have
added in the pom.xml le.

For example, If spring-data-jpa is in the classpath, then it


automatically tries to con gure a DataSource by reading the database
properties from application.properties le.

@ComponentScan : It tells Spring to scan and bootstrap other components


de ned in the current package (com.example.easynotes) and all the sub-
packages.

The main() method calls Spring Boot’s SpringApplication.run()


method to launch the application.

2. resources/

This directory, as the name suggests, is dedicated to all the static resources,
templates and property les.

resources/static - contains static resources such as css, js and images.


C ALLIC ODE R

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

resources/templates - contains server-side templates which are rendered


by Spring.

resources/application.properties - This le is very important. It contains


application-wide properties. Spring reads the properties de ned in this le
to con gure your application. You can de ne server’s default port, server’s
context path, database URLs etc, in this le.

You can refer this page for common application properties used in Spring
Boot.

3. EasyNotesApplicationTests - De ne unit and integration tests here.

4. pom.xml - contains all the project dependencies

Con guring MySQL Database

As I pointed out earlier, Spring Boot tries to auto-con gure a DataSource if


spring-data-jpa is in the classpath by reading the database con guration
from application.properties le.

So, we just have to add the con guration and Spring Boot will take care of the
rest.

Open application.properties le and add the following properties to it.

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourcePro


spring.datasource.url = jdbc:mysql://localhost:3306/notes_app?use
spring.datasource.username = root
spring.datasource.password = root

## 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

# Hibernate ddl auto (create, create-drop, validate, update)


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.

The property spring.jpa.hibernate.ddl-auto is used for database


initialization. I’ve used the value “update” for this property.

It does two things -

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.

Using update for spring.jpa.hibernate.ddl-auto property is ne for


development. But, For production, You should keep the value of this property
to “validate”, and use a database migration tool like Flyway for managing
changes in the database schema.

Creating the Note model

All right! Let’s now create the Note model. Our Note model has following
elds -

id : Primary Key with Auto Increment.


C ALLIC ODE R
title : The title of the Note. (NOT NULL eld)
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 6/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder

content : Note’s content. (NOT NULL eld)


createdAt : Time at which the Note was created.
updatedAt : Time at which the Note was updated.

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;

// Getters and Setters ... (Omitted for brevity)


}

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.

@Id annotation is used to de ne the primary key.

@GeneratedValue annotation is used to de ne the primary key


generation strategy. In the above case, we have declared the primary key
to be an Auto Increment eld.

@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.

By default, a eld named createdAt is mapped to a column named


created_at in the database table. i.e. all camel cases are replaced with
underscores.

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;

@Temporal annotation is used with java.util.Date and


java.util.Calendar classes. It converts the date and time values from
Java Object to compatible database type and vice versa.

@JsonIgnoreProperties annotation is a Jackson annotation. Spring


Boot uses Jackson for Serializing and Deserializing Java objects to and from
JSON.

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.

Enable JPA Auditing

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.

To achieve this, we need to do two things -

1. Add Spring Data JPA’s AuditingEntityListener to the domain model.

We have already done this in our Note model with the annotation
@EntityListeners(AuditingEntityListener.class) .

2. Enable JPA Auditing in the main application.

Open EasyNotesApplication.java and add @EnableJpaAuditing


annotation.

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 {

public static void main(String[] args) {


SpringApplication.run(EasyNotesApplication.class, args);
}
}

Creating NoteRepository to access data from the


database

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

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.

Checkout all the methods available from SimpleJpaRepository’s


documentation.

Creating Custom Business Exception

We’ll de ne the Rest APIs for creating, retrieving, updating, and deleting a
Note in the next section.

The APIs will throw a ResourceNotFoundException whenever a Note with


a given id is not found in the database.

Following is the de nition of ResourceNotFoundException . (I’ve created a


package named exception inside com.example.easynotes to store this
exception class) -

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

private Object fieldValue;

public ResourceNotFoundException( String resourceName, String


super(String.format("%s not found with %s : '%s'", resour
this.resourceName = resourceName;
this.fieldName = fieldName;
this.fieldValue = fieldValue;
}

public String getResourceName() {


return resourceName;
}

public String getFieldName() {


return fieldName;
}

public Object getFieldValue() {


return fieldValue;
}
}

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.

First, create a new package controller inside com.example.easynotes .


C ALLIC ODE R
Then, create a new class NoteController.java with the following contents
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 12/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder

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;

// Get All Notes

// Create a new Note

// Get a Single Note

// Update a Note

// Delete a Note
}

@RestController annotation is a combination of Spring’s @Controller


C ALLIC ODE R
and @ResponseBody annotations.
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 13/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder

The @Controller annotation is used to de ne a controller and the


@ResponseBody annotation is used to indicate that the return value of a
method should be used as the response body of the request.

@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.

1. Get All Notes (GET /api/notes)

// Get All Notes


@GetMapping("/notes")
public List<Note> getAllNotes() {
return noteRepository.findAll();
}

The above method is pretty straightforward. It calls JpaRepository’s


findAll() method to retrieve all the notes from the database and returns
the entire list.

Also, The @GetMapping("/notes") annotation is a short form of


@RequestMapping(value="/notes", method=RequestMethod.GET) .

2. Create a new Note (POST /api/notes)

// Create a new Note


@PostMapping("/notes")
public Note createNote(@Valid @RequestBody Note note) {
return noteRepository.save(note);
}

The @RequestBody annotation is used to bind the request body with a


method parameter.
C ALLIC ODE R

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.

3. Get a Single Note (Get /api/notes/{noteId})

// Get a Single Note


@GetMapping("/notes/{id}")
public Note getNoteById(@PathVariable(value = "id") Long noteId)
return noteRepository.findById(noteId)
.orElseThrow(() -> new ResourceNotFoundException("Not
}

The @PathVariable annotation, as the name suggests, is used to bind a


path variable with a method parameter.

In the above method, we are throwing a ResourceNotFoundException


whenever a Note with the given id is not found.

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).

4. Update a Note (PUT /api/notes/{noteId})

// 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

.orElseThrow(() -> new ResourceNotFoundException("Not

note.setTitle(noteDetails.getTitle());
note.setContent(noteDetails.getContent());

Note updatedNote = noteRepository.save(note);


return updatedNote;
}

5. Delete a Note (DELETE /api/notes/{noteId})

// 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();
}

Running the Application

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.

Great! Now, It’s time to test our apis using postman.

Testing the APIs

Creating a new Note using POST /api/notes API

Retrieving all Notes using GET /api/notes API

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

Retrieving a single Note using GET /api/notes/{noteId} API

Updating a Note using PUT /api/notes/{noteId} API

Deleting a Note using DELETE /api/notes/{noteId} API

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

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.

Thank you for reading. Please ask any questions in the comment section
below.

Liked the Article? Share it on Social media!

Facebook Twitter Google+ Linkedin

Pinterest

Looking for more posts like this?


C ALLIC ODE R
Join our growing community of developers!
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 19/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder

Your Email I'm in

68 Comments CalliCoder 
1 Login

Sort by Best
 Recommend 11 ⤤ Share

Join the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Name

Віталій Суслін • 2 months ago


Thank you !!!!! It`s the best simple tutorial !!! It`s works in the end !!!! Nice explanation
about little details !!!
1△ ▽ • Reply • Share ›

simohamed hammadi • 2 months ago


Great Job ,
it's work in the first time ,
good explain and more details
1△ ▽ • Reply • Share ›

Nguyễn Quốc Giang • 3 months ago


Thank you, it's a very nice post and easy to understand
1△ ▽ • Reply • Share ›

Jonathan Gibran Hernandez Antu • 3 months ago


So great my friend
1△ ▽ • Reply • Share ›

Manish Kumar • 4 months ago


Hi Rajeev,
i try to run this code in my local , while post method it throw error
"timestamp": 1512579518960,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.DataIntegrityViolationException",
"message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is
org.hibernate.exception.ConstraintViolationException: could not execute statement",
what i understand
C ALLIC
returnODE R
noteRepository.save(note);// having null value

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

kindly guide me to run same


Regards
Manish
1△ ▽ • Reply • Share ›

Rajeev Kumar Singh Mod > Manish Kumar • 4 months ago

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 ›

Manish Kumar > Rajeev Kumar Singh • 3 months ago


Thanks, it is working now.

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 ›

BALACHANDRA RAJU • 4 months ago


Thanks a lot for nice article...
1△ ▽ • Reply • Share ›

Alaa Mahmoud • 4 months ago


thank you for this awesome tutorial i learn a lot from it
1△ ▽ • Reply • Share ›

Rajeev Kumar Singh Mod > Alaa Mahmoud • 4 months ago

Happy to hear that. Cheers :)


△ ▽ • Reply • Share ›

Pruthvi Uvss • 5 months ago


com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '' for
column 'created_at' at row 1

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 ›

levijatanus > Pruthvi Uvss • 5 months ago


Solved this problem by replacing Note class @CreateDate to
@CreationTimestamp
like this:

@Column(nullable = false, updatable = false)


@Temporal(TemporalType.TIMESTAMP)
@CreationTimestamp
C ALLIC ODE R
private Date createdAt;
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 21/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder

@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@UpdateTimestamp
private Date updatedAt;
△ ▽ • Reply • Share ›

Rajeev Kumar Singh Mod > levijatanus • 5 months ago

That's great man! Thank you for sharing the info :)


△ ▽ • Reply • Share ›

Rajeev Kumar Singh Mod > Pruthvi Uvss • 5 months ago

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 ›

Pruthvi Uvss > Rajeev Kumar Singh • 5 months ago


I used them from the beginning but still I got that error.
1△ ▽ • Reply • Share ›

Rajeev Kumar Singh Mod > Pruthvi Uvss • 5 months ago

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 ›

Pruthvi Uvss > Rajeev Kumar Singh • 5 months ago


https://github.com/pruthviu... ... I found no difference between
implementations. please check and confirm. The error still persists.
△ ▽ • Reply • Share ›

Rajeev Kumar Singh Mod > Pruthvi Uvss • 5 months ago

Hi Pruthvi,

I checked the code. It was an issue with the mysql-connector-java


version in the pom.xml file. The included version was 3.1.14 which is
way older than the recent versions. You can just remove the version
information from mysql-connector-java dependency and spring boot
will use the latest version which is compatible with the spring-boot
release. For the spring-boot version you're using (1.5.1.RELEASE),
the default mysql-connector-java version is 5.1.40.

I just removed version information from mysql-connector-java


dependency and it started working :)
C ALLIC ODE R △ ▽ • Reply • Share ›

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

Pruthvi Uvss > Rajeev Kumar Singh • 5 months ago


Thanks man! It worked. I appreciate ur help.
14 △ ▽ • Reply • Share ›

S.Nkm • 7 months ago


Thank you for writing this. It's useful, informative, and you kept it simple.
1△ ▽ • Reply • Share ›

Omar Vazquez • 8 months ago


Tank you for this great post. Initially it did not work, because i create by mistake the
package "controller" after a while when i noticed i changed the package to
"com.example.easynotes.controller" and presto¡.
1△ ▽ • Reply • Share ›

Rajeev Kumar Singh Mod > Omar Vazquez • 7 months ago

Awesome! Glad that it worked in the end. :-)


△ ▽ • Reply • Share ›

Osman Otoniel Mazariegos Mende • 9 hours ago


thanks for your contributions, can you help me, Error creating bean with name
'entityManagerFactory' defined in class path resource
△ ▽ • Reply • Share ›

Rajeev Kumar Singh Mod > Osman Otoniel Mazariegos Mende • 9 hours ago

Hi,

You might wanna check the following things -

1. Have you created a mysql database named notes_app?


2. Have you specified the spring.datasource.username and
spring.datasource.password properties as per your MySQL installation?

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 ›

Osman Otoniel Mazariegos Mende • 9 hours ago


hola
△ ▽ • Reply • Share ›

Pablo Cruz • a day ago


Great tutorial, simple but functional with a lot of good spring material
△ ▽ • Reply • Share ›
C ALLIC ODE R
saurabh sharma • 14 days ago
Hello I have successfully completed with this application and till get method it is working
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 23/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder
Hello I have successfully completed with this application and till get method it is working
properly when ever i try to insert some values using post method it is not working so can u
guide me.
and i am using xampp server for mysql is it fine.
and how can i add more forms and moudles to get a complete application.
please guide me so that i can be good at it.
△ ▽ • Reply • Share ›

Got Motivation • 15 days ago


Wow. Nice Job. Clear content with good appearance. Keep it up for the who would like to
learn new technology. Thank you.
△ ▽ • Reply • Share ›

Arun Singh • 17 days ago


great help dude. Thanks
△ ▽ • Reply • Share ›

Fikri Khoirurohman • 18 days ago


Thank you. Nice article, i am just started learning java, and it's work
△ ▽ • Reply • Share ›

Manjunath Gundra • 21 days ago


Thanks for posting.
I am getting the below error.

Exception encountered during context initialization - cancelling refresh attempt:


org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean
with name 'noteController': Unsatisfied dependency expressed through field
'noteRepository'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean
of type 'com.example.easynotes.repository.NoteRepository' available: expected at least 1
bean which qualifies as autowire candidate. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}

could you please help me out!!


△ ▽ • Reply • Share ›

Rajeev Kumar Singh Mod > Manjunath Gundra • 21 days ago

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 ›

Rajeev Kumar Singh Mod > Manjunath Gundra • 21 days ago

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 ›

Manjunath Gundra > Rajeev Kumar Singh • 21 days ago


Cloned your code.. it's working fine.. Thanks dude!! cheers..
△ ▽ • Reply • Share ›

Matthew Mahut • a month ago


Thank you very much for AWESOME TUTORIAL!!!
Works like a charm on first run!
Very good explanation in detail!
You've have chosen important and interesting features ;-)
△ ▽ • Reply • Share ›

vignesh • a month ago


It looks like you have added few headers in the postman window. what are they and why
we need them?
△ ▽ • Reply • Share ›

Milos Zivkovic • a month ago


Very useful,
but how would you do partial update? Because you are validating body on update, you
must always provide all fields.
C ALLIC
△ ▽ODE R • Share ›
• Reply

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

Daniel Matos • a month ago


awesome tutorial !
△ ▽ • Reply • Share ›

Ghassen Khalil Ati • a month ago


In the Controller, you should change Note note = noteRepository.findOne(noteId) to
noteRepository.getOne(noteId)
△ ▽ • Reply • Share ›

Mounira Sghari • a month ago


Error :"Error starting ApplicationContext. To display the auto-configuration report re-run
your application with 'debug' enabled.
2018-02-11 22:33:06.061 ERROR 3408 --- [ restartedMain] o.s.boot.SpringApplication :
Application startup failed"
△ ▽ • Reply • Share ›

jonKlon • 2 months ago


Ur spring hibernate example awesome for nubie like me.... Jozzz.....
△ ▽ • Reply • Share ›

Richa • 2 months ago


I am getting following error
No bean named 'entityManagerFactory' available

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 ›

Rajeev Kumar Singh Mod > Richa • a month ago

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 ›

Manoj Tarkar • 2 months ago


Can You please share header values for post method.
△ ▽ • Reply • Share ›

Rajeev Kumar Singh Mod > Manoj Tarkar • 2 months ago

@Manoj Tarkar You only need a single header - Content-Type: application/json.


Nothing else!
C ALLIC ODE R
I know, the Postman screenshots in the article are showing extra headers. Those
https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 26/28
26/03/2018 Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder

headers might have been stored from any request to a different service.
△ ▽ • Reply • Share ›

Manoj Tarkar > Rajeev Kumar Singh • 2 months ago


Thanks Rajeev, I am using same bu

ue.
5△ ▽ • Reply • Share ›

Manoj Tarkar • 2 months ago


Getting error
pOST:
header
{
"title": "test",
"content": "This"
}

{
"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 ›

Rajeev Kumar Singh Mod > Manoj Tarkar • 2 months ago

Hi Manoj, You need to pass the title and content fields in the body of the request

About Privacy Copyright © CalliCoder


Sitemap 2017

https://www.callicoder.com/spring-boot-rest-api-tutorial-with-mysql-jpa-hibernate/ 28/28

You might also like