Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial _ CalliCoder

Share Embed Donate


Short Description

Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial _ CalliCoder...

Description

26/03/2018

Spring Boot, MySQL, JPA, Hibernate Restful CRUD API Tutorial | CalliCoder

Raje Ra jeev ev Kum Kumar ar Si Sing ngh h • Sp Spri ring ng Bo Boot ot • Ju Jull 3, 20 2017 17 • 12 mi mins ns re read ad

CALLICODER

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

Spring Initializer http://start.spring.io

http://start.spring.io

CALLICODER

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

package com.example.easynotes;

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplicati CALLICODER

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

@Conguration

@EnableAutoConguration

@ComponentScan

CALLICODER

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

this page

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

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

Flyway

CALLICODER

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

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; import java.util.Date;  Java 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; CALLICODER

@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) }

CALLICODER

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;

CALLICODER

@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); } }

JpaRepository

SimpleJpaRepository

package com.example.easynotes.repository;

import com.example.easynotes.model.Note; import org.springframework.data.jpa.repository.JpaRepository;

@Repository public interface NoteRepository extends JpaRepository CALLICODER

} 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

SimpleJpaRepository’s documentation

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;

CALLICODER

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; } }

CALLICODER

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 }

CALLICODER

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

// Get All Notes @GetMapping("/notes") public List getAllNotes() { return noteRepository.findAll(); }

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

CALLICODER

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

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

// Update a Note @PutMapping("/notes/{id}") public Note updateNote(@PathVariable(value = "id") Long noteId, @Valid @RequestBody Note CALLICODER

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; }

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

$ mvn spring-boot:run CALLICODER

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

CALLICODER

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

CALLICODER

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

my github repository

Facebook

Twitter

Google+

Linkedin

Pinterest

Looking for more posts like this? CALLICODER

 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

68 Comments

I'm in

1 Login 

CalliCoder

Sort by Best

⤤ Share

  Recommend 11

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 CALLICODER

return 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 CALLICODER 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 :) CALLICODER

• 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. • Reply • Share ›

14

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 › CALLICODER

saurabh sharma • 14 days ago

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

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 ›

CALLICODER

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. • Share › C A L L I C O •DReply ER

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 ›

onKlon • 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! CALLICODER

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", C A "NotBlank.content", LLICODER "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 Mano You need to ass the title and content fields in the bod of the re uest

About

Privacy

Sitemap

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

Copyright © CalliCoder 2017

28/28

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF