2023-02-05 10:20:44
ModdelMapper 사용 정리
Entity <-> DTO변환에 사용하기 위해 알게된 메서드고 일반적으로 사용할 경우가 있을때를 써놓았다.
NullpointException 정리
java.lang.IllegalArgumentException: source cannot be null
Entity DTO간 변환할 때, 모든 DTO에 값이 들어가진 않으므로 이런 오류가 뜬다.
그런 경우 아래와 따로 기본 생성자로 처리하는 메서드를 구현하여 사용한다.
ex.1)
package com.genie.myapp.Config;
import org.modelmapper.ModelMapper;
public class CustomerModelMapper extends ModelMapper {
@Override
public <D> D map(Object source, Class<D> destinationType) {
Object tmpSource = source;
if(source == null){
tmpSource = new Object(); // 기본 생성자로 생성 처리
}
return super.map(tmpSource, destinationType);
}
}
ex.2)
@Bean
public ModelMapper modelMapper() {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setPropertyCondition(Conditions.isNotNull());
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
return modelMapper;
사용방식
아래와 같이 기본 CustomModelMapper를 형변환 하여 사용한다.
그러나 복합키나 외래키의 경우 STRICT 조건으로 Entity와 DTO간 변환을 할 경우,
키 값에 Null이 입력되는데 이는 연관관계 메서드로 해결이 되지 않는다.
왜냐하면 Entity와 DTO의 변환에서 생긴 Null값인 것이 첫번째고
두번째는 DTO에선 "String example;" 이라면 Entity에선 "User example;"
이기에 타입에서 차이가 생기기 때문에 입력이 안된다.
굳이 아래와 같이 사용하지 않고 입력 받으려면
DTO객체에서도 User example; 이라고 하면 되지만 잘 생각해보면 문제가 있다
// Entity -> DTO (정적 팩토리 메서드)
public static AddressDTO convertEntityToDTO(Address address){
ModelMapper modelMapper = new CustomerModelMapper();
// 매핑 전략 설정
modelMapper.getConfiguration().setMatchingStrategy(STRICT);
return modelMapper.map(address,AddressDTO.class);
}
// DTO -> Entyty
public static Address convertDTOtoEntity(AddressDTO addressDTO) {
ModelMapper modelMapper = new CustomerModelMapper();
// 매핑 전략 설정
modelMapper.getConfiguration().setMatchingStrategy(STRICT);
//외래키 해결
modelMapper.addMappings(new PropertyMap<AddressDTO, Address>() {
@Override
protected void configure() {
map().getGenieId().setGenieId(source.getGenieId());
}
});
return modelMapper.map(addressDTO, Address.class);
}
그럴땐 // 외래키 해결 부분처럼 따로 PropertyMap을 이용해서 추가 설정을 해서 입력을해준다.
List 전환
// Entity -> DTO (List의 경우)
public static List<OrderDTO> convertEntityToDTO(List<MyOrder> orderList) {
return orderList.stream().map(OrderDTO::convertEntityToDTO).collect(Collectors.toList());
//목록을 스트림으로//스트림에 담긴 OrderDTO 클래스의 E->D로 변환된 D스트림 반환 //스트림을 다시 DTO로 변환
}
// Entity <- DTO (List의 경우)
public static List<MyOrder> convertDTOToEntity(List<OrderDTO> orderList) {
return orderList.stream().map(OrderDTO::convertDTOtoEntity).collect(Collectors.toList());
//목록을 스트림으로 // 스트림에 담긴 OrderDTO 클래스의 E->D로 변환된 D스트림 반환 //스트림을 다시 DTO로 변환
}
'개발' 카테고리의 다른 글
도메인의 정의 (0) | 2024.08.02 |
---|---|
modelmapper 문제 발생 (0) | 2024.08.01 |
@Autowired 대신 생성자주입을 이용하자 (0) | 2024.08.01 |
주문결제 페이지 오류발생 (0) | 2024.08.01 |
JPA: Invalid Path:~~ (0) | 2024.08.01 |