티스토리 뷰



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