티스토리 뷰
ModelMapper enables to convert DTO to an entity.
DTO를 이용 id 값을 드러내지 않게한다.
사용된 DTO를 entity(User class) 로 다시 변경하기위해 ModelMapper를 사용
You need to add ModelMapper bean at @SpringBootApplication. It let us use ModelMapper in different classes.
ModelMapper @Bean을 @SpringBootApplication에 등록한다.
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public ModelMapper modelmapper(){
return new ModelMapper();
}
}
import ModelMapper in a UsersController.
Use ModelMapper.map() method to convert DTO to an entity.
package travelmate.demo.Users;
//import ModelMapper
import org.modelmapper.ModelMapper;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@RequestMapping("/user")
public class UsersController {
private final UsersRepository usersRepository;
private final ModelMapper modelMapper;
public UsersController(UsersRepository usersRepository, ModelMapper modelMapper){
this.usersRepository = usersRepository;
this.modelMapper = modelMapper;
}
@PostMapping
public ResponseEntity insertUser(@RequestBody @Valid UserDto userDto, Errors errors) {
if(errors.hasErrors()){
return ResponseEntity.badRequest().body(errors);
}
//conversion from userDto to an entity
User user = modelMapper.map(userDto, User.class);
//Use save method of JpaRepository to save entity
User createdUser = usersRepository.save(user);
return ResponseEntity.ok().body(createdUser);
}
@GetMapping
public ResponseEntity signIn() {
return ResponseEntity.ok().body(null);
}
}
reference
https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application
'Spring Boot' 카테고리의 다른 글
DTO(Data Transfer Object) 와 ModelMapper (0) | 2019.03.10 |
---|---|
Constructor Injection (0) | 2019.03.08 |
Creating Spring Boot application with IntelliJ II (0) | 2019.02.27 |
Creating Spring Boot application with IntelliJ (0) | 2019.02.27 |
@RestController (0) | 2019.02.10 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Object type casting
- Collection Framework
- code refactoring
- hackerrank
- repeat()
- Javascript Algorithm
- equals()
- rest parameter
- HackerRank Algorithm
- 프로그래머스 알고리즘문제
- math.max
- java
- javascript
- easy algorithm
- spring boot application
- algorithm
- hackerrank javascript solution
- C++
- hackerrank solution
- ... in Javascript
- math.abs
- 프로그래머스
- string class in java
- 알고리즘
- hackerrank javascript
- substring()
- easy javascript algorithm
- 프로그래머스 알고리즘
- HashMap
- compareTo()
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함