2
2
.
.
1
1
2
2
.
.
1
1
M
M
a
a
n
n
u
u
a
a
l
l
l
l
y
y
I
I
n
n
f
f
o
o
This tutorial shows how to manually Convert DTO into Entities.
Tutorial Annotation - (Spring) @RequestBody shows how to convert JSON data from HTTP Request into DTO.
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables @Controller and @RequestMapping. Includes Tomcat Server.
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: service (add Spring Boot Starters from the table)
Create Package: entities (inside main package)
Create Class: Author.java (inside package entities)
Create Class: Book.java (inside package entities)
Create Package: DTOs (inside main package)
Create Class: AuthorBookDTO.java (inside package controllers)
Create Package: controllers (inside main package)
Create Class: MyController.java (inside package controllers)
Author.java
package com.ivoronline.springboot_dto_modelmapper.entities;
public class Author {
public Integer id;
public String name;
public Integer age;
}
Book.java
package com.ivoronline.springboot_dto_modelmapper.entities;
public class Book {
public Integer id;
public String title;
}
MyController
AuthorBookDTO
Postman
http://localhost:8080/AddAuthor
Author
Book
HTTP POST Request
AuthorBookDTO.java
package com.ivoronline.springboot_dto_modelmapper.DTOs;
public class AuthorBookDTO {
public String name;
public Integer age;
public String title;
}
MyController.java
package com.ivoronline.springboot_dto_modelmapper.controllers;
import com.ivoronline.springboot_dto_modelmapper.DTOs.AuthorBookDTO;
import com.ivoronline.springboot_dto_modelmapper.entities.Author;
import com.ivoronline.springboot_dto_modelmapper.entities.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("AddAuthorBook")
public String addAuthorBook(@RequestBody AuthorBookDTO authorBookDTO) {
//CONVERT DTO TO AUTHOR ENTITY
Author author = new Author();
author.name = authorBookDTO.name;
author.age = authorBookDTO.age;
//CONVERT DTO TO BOOK ENTITY
Book book = new Book();
book.title = authorBookDTO.title;
//RETURN SOMETHING
return author.name + " has written " + book.title;
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
Start Postman
POST: http://localhost:8080/AddAuthorBook
Headers: (copy from below)
Body: (copy from below)
Send
Headers (add Key-Value)
Content-Type: application/json
Body (option: raw)
{
"name" : "John",
"age" : 20
"title" : "Book about dogs"
}
HTTP Response Body
John has written Book about dogs
HTTP Request Headers (Bulk Edit) Request JSON Body (raw) & Response Body
Application Structure
pomx.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>