728x90
반응형
🍟 dto <> entity 변환 시, mapstruct 라이브러리를 사용하는 방법이 있다.
세팅 :
build.gradle
dependencies {
//MapStruct
annotationProcessor 'org.mapstruct:mapstruct-processor:1.4.2.Final'
implementation 'org.mapstruct:mapstruct:1.4.2.Final'
}
mapper
* UserMapper로 구현함.
package com.org.walk.user;
import com.org.walk.util.EntityMapper;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@Mapper
public interface UserMapper extends EntityMapper<UserDto, UserEntity> {
UserMapper mapper = Mappers.getMapper(UserMapper.class);
}
EntityMapper
package com.org.walk.util;
public interface EntityMapper<D, E> {
E toEntity(final D dto);
D toDto(final E entity);
}
service 단에서 사용 시, 다음과 같음
package com.org.walk.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserServiceImpl implements UserService {
@Override
public void postUser(UserDto userDto) throws Exception {
UserEntity userEntity = UserMapper.mapper.toEntity(userDto);
userRepository.save(userEntity);
}
}
320x100
반응형
'JAVA > SPRING' 카테고리의 다른 글
[Spring] Spring / Spring boot 특징 간단 정리. (0) | 2023.01.11 |
---|---|
[NAVER maps 길 찾기] springboot + webClient 로 API 호출 (0) | 2022.09.02 |
spring boot / H2 DB 세팅 (0) | 2022.05.29 |
Hikari CP / Spring boot 설정 (0) | 2022.05.23 |
QueryDSL , Criteria , Native Query (0) | 2022.05.09 |