Spring Boot
ModelMapper DTO-entity conversion
seoca
2019. 3. 8. 04:14
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