코딩/Spring

[Spring] 스프링 modelmapper Java Entity Dto 매핑

it 끄적이기 2022. 11. 3. 15:08

Spring modelmapper Java Entity Dto 매핑하는 방법

1. 의존성 추가

build.gradle 파일에 ModelMapper 의존성을 추가합니다.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.modelmapper:modelmapper:2.4.2'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

2. Entity와 DTO 클래스 작성

먼저, Entity 클래스와 DTO 클래스를 작성합니다. 여기에서는 Person Entity와 PersonDto DTO를 사용

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String lastName;
    private String email;
    private LocalDate birthday;
    // getter/setter 메소드 생략
}

public class PersonDto {
    private Long id;
    private String firstName;
    private String lastName;
    private String email;
    private String birthday;
    // getter/setter 메소드 생략
}

3. ModelMapper 설정

Spring Boot에서는 ModelMapper를 Bean으로 등록하여 사용할 수 있습니다. 이를 위해, 다음과 같이 @Configuration 어노테이션을 사용하여 ModelMapper Bean을 등록

@Configuration
public class AppConfig {
    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }
}

4. Entity와 DTO 매핑

Person Entity를 PersonDto DTO로 매핑하는 예제입니다. 조회된 Person Entity를 PersonDto DTO로 매핑하고, birthday 필드를 문자열로 변경합니다.

@Service
public class PersonService {
    @Autowired
    private PersonRepository personRepository;
    @Autowired
    private ModelMapper modelMapper;

    public PersonDto getPerson(Long id) {
        Person person = personRepository.findById(id).orElse(null);
        if (person == null) {
            return null;
        }

        PersonDto personDto = modelMapper.map(person, PersonDto.class);
        personDto.setBirthday(person.getBirthday().toString());

        return personDto;
    }
}

5. DTO 사용

PersonDto DTO를 컨트롤러에서 사용

@RestController
@RequestMapping("/person")
public class PersonController {
    @Autowired
    private PersonService personService;

    @GetMapping("/{id}")
    public ResponseEntity<PersonDto> getPerson(@PathVariable Long id) {
        PersonDto person