• No results found

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

N/A
N/A
Protected

Academic year: 2021

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

Copied!
28
0
0

Loading.... (view fulltext now)

Full text

(1)

Ra

Rajejeev ev KumKumar ar SiSingngh h • • SpSpriring ng BoBoot ot • • JuJul l 3, 3, 202017 17 • • 12 12 mimins ns rereadad

C A L L I C O D E R

(2)

Spring Initializer

Spring Initializer

http://start.spring.io

http://start.spring.io

http://start.spring.io

http://start.spring.io

C A L L I C O D E R C A L L I C O D E R

(3)

package com.example.easynotes;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplicati

C A L L I C O D E R

(4)

@Conguration

@EnableAutoConguration

@ComponentScan

@SpringBootApplication

public class EasyNotesApplication {

public static void main(String[] args) {

SpringApplication.run(EasyNotesApplication.class, args);

}

}

(5)

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

(6)

Flyway

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

spring.jpa.hibernate.ddl-auto = update

(7)

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.*;

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;

@Column(nullable = false, updatable = false)

C A L L I C O D E R

Search CalliCoder 

 Java

Kotlin

Golang

Spring Boot

Node.js

JavaFX

(8)

@Temporal(TemporalType.TIMESTAMP)

@CreatedDate

private Date createdAt;

@Column(nullable = false)

@Temporal(TemporalType.TIMESTAMP)

@LastModifiedDate

private Date updatedAt;

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

}

(9)

@Column(name = "created_on")

private String createdAt;

@SpringBootApplication

C A L L I C O D E R

(10)

JpaRepository

SimpleJpaRepository

@EnableJpaAuditing

public class EasyNotesApplication {

public static void main(String[] args) {

SpringApplication.run(EasyNotesApplication.class, args);

}

}

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>

}

(11)

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;

private String fieldName;

C A L L I C O D E R

(12)

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;

}

}

C A L L I C O D E R

(13)

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

}

(14)

// Get All Notes

@GetMapping("/notes")

public List<Note> getAllNotes() {

return noteRepository.findAll();

}

// Create a new Note

@PostMapping("/notes")

public Note createNote(@Valid @RequestBody Note note) {

return noteRepository.save(note);

}

(15)

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

Note note = noteRepository.findById(noteId)

C A L L I C O D E R

(16)

$ mvn spring-boot:run

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

}

(17)
(18)
(19)

my github repository

Facebook

Twitter

Google+

Linkedin

Pinterest

Looking for more posts like this?

 Join our growing community of developers!

C A L L I C O D E R

(20)

Your Email I'm in

68 Comments

CalliCoder

1

Login

 Share

Sort by Best

LOG IN WITH OR SIGN UP WITH DISQUS Name

Join the discussion…

?

• Reply •

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

Thank you !!!!! It`s the best simple tutorial !!! It`s works in the end !!!! Nice explanation about little details !!!

1

• Reply •

simohamed hammadi• 2 months ago

Great Job ,

it's work in the first time ,

good explain and more details

1

• Reply •

Nguyễn Quốc Giang•3 months ago

Thank you, it's a very nice post and easy to understand

1

• Reply •

Jonathan Gibran Hernandez Antu •3 months ago

So great my friend

1

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

return noteRepository.save(note);// having null value  Recommend  11 Share › Share › Share › Share › C A L L I C O D E R

(21)

• Reply •

Regards Manish

1

• Reply •

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 •

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 •

BALACHANDRA RAJU • 4 months ago

Thanks a lot for nice article...

1

• Reply •

Alaa Mahmoud •4 months ago

thank you for this awesome tutorial i learn a lot from it

1

• Reply •

Rajeev Kumar Singh Mod > Alaa Mahmoud• 4 months ago

Happy to hear that. Cheers :)

• Reply •

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

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

private Date createdAt;

Share › Share › Share › Share › Share › Share › Share › C A L L I C O D E R

(22)

• Reply •

@Column(nullable = false)

@Temporal(TemporalType.TIMESTAMP) @UpdateTimestamp

private Date updatedAt;

• Reply •

Rajeev Kumar Singh Mod > levijatanus• 5 months ago

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

• Reply •

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 •

Pruthvi Uvss> Rajeev Kumar Singh• 5 months ago

I used them from the beginning but still I got that error.

1

• Reply •

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 •

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 •

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

Share › Share › Share › Share › Share › Share › Share › C A L L I C O D E R

(23)

• Reply •

Thanks man! It worked. I appreciate ur help.

14

• Reply •

S.Nkm•7 months ago

Thank you for writing this. It's useful, informative, and you kept it simple.

1

• Reply •

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 •

Rajeev Kumar Singh Mod > Omar Vazquez•7 months ago

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

• Reply •

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 •

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 •

Osman Otoniel Mazariegos Mende•9 hours ago

hola

• Reply •

Pablo Cruz •a day ago

Great tutorial, simple but functional with a lot of good spring material

saurabh sharma•14 days ago

Share › Share › Share › Share › Share › Share › Share › Share › C A L L I C O D E R

(24)

• Reply •

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 •

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 •

Arun Singh •17 days ago

great help dude. Thanks

• Reply •

Fikri Khoirurohman •18 days ago

Thank you. Nice article, i am just started learning java, and it's work

• Reply •

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 •

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.

Manjunath Gundra> Rajeev Kumar Singh•21 days ago

Rajeev - I did.. please find the same in the below screenshot

Share › Share › Share › Share › Share › Share › C A L L I C O D E R

(25)

• Reply •

• Reply •

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 •

Manjunath Gundra> Rajeev Kumar Singh•21 days ago

Cloned your code.. it's working fine.. Thanks dude!! cheers..

• Reply •

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 •

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 •

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 › Share › Share › Share › Share › Share › C A L L I C O D E R

(26)

• Reply •

awesome tutorial !

• Reply •

Ghassen Khalil Ati• a month ago

In the Controller, you should change Note note = noteRepository.findOne(noteId) to noteRepository.getOne(noteId)

• Reply •

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 •

onKlon• 2 months ago

Ur spring hibernate example awesome for nubie like me.... Jozzz...

• Reply •

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 •

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 •

Manoj Tarkar • 2 months ago

Can You please share header values for post method.

Rajeev Kumar Singh Mod > Manoj Tarkar • 2 months ago

@Manoj Tarkar 

 You only need a single header - Content-Type: application/json. Nothing else!

I know, the Postman screenshots in the article are showing extra headers. Those

Share › Share › Share › Share › Share › Share › Share › C A L L I C O D E R

(27)

• Reply •

• Reply •

Manoj Tarkar > Rajeev Kumar Singh• 2 months ago

Thanks Rajeev, I am using same bu

ue.

5

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", "NotBlank" Share › C A L L I C O D E R

(28)

About Privacy Sitemap Copyright © CalliCoder 2017 • Reply • see more

Rajeev Kumar Singh Mod > Manoj Tarkar • 2 months ago

Hi Mano You need to ass the titleand content fields in the bod of the re uest Share ›

References

Related documents