JVM/Java

[Java] 객체 매핑 라이브러리 ModelMapper 살펴보자

헹창 2022. 8. 17.
반응형

ModelMapper ?

서로 다른 클래스의 값을 한 번에 복사하게 도와주는 라이브러리로,

어떤 Object (Source Object) 에 있는 필드 값들을 자동으로 원하는 Object (Destination Object) 에 매핑 시켜주는 라이브러리다.

ModelMapper 공식 문서

 

주로 DTO와 같은 클래스로 데이터를 받은 후 원하는 클래스(Entity)에 넣어줄 때, Getter/Setter를 이용해 필드를 복사/붙여넣기하는 작업을 거친다. 이 때, 매핑해야할 필드가 다른 경우도 빈번하다. 즉, 다른 모델의 Object를 매핑해줘야하는 작업이 발생할 수 있다. 이런 단점들을 해결하기 위한 라이브러리이다.

 

세팅

의존성 추가

  • build.gradle
implementation 'org.modelmapper:modelmapper:2.4.2'

 

ModelMapper 살펴보기

예제 클래스

/* 모든 클래스 Constructor, Getter, Setter 생략 */

class Address {
    String street;
    String city;
}

class Name {
    String firstName;
    String lastName;
}

class Customer {
    Name name;
}

class OrderDto {
    String customerFirstName;
    String customerLastName;
    String billingStreet;
    String billingCity;
}

ModelMapper 객체 매핑

ModelMapper.map(Object source, Class<D> destinationType)
  • 객체 변환 매핑 예시
Order order = new Order(
        new Customer(new Name("FIRSTNAME", "LASTNAME")),
        new Address("STREET", "CITY")
);

ModelMapper modelMapper = new ModelMapper();

OrderDto result = modelMapper.map(order, OrderDto.class);
  • 실행 결과
result = {
	customerFirstName = "FIRSTNAME"
	customerLastName = "LASTNAME"
	billingStreet = "STREET"
	billingCity = "CITY"
}

각 클래스 프로퍼티들의 연관관계를 자동으로 판단하여 매핑이 되었다.

 

이처럼 ModelMapper 에서는 map(source, destination) 메소드가 호출되면 sourcedestination 타입을 분석하여 매칭 전략 및 기타 설정값에 따라 일치하는 속성을 결정하여 매칭 항목에 대해 데이터를 매핑한다.

 

위처럼 sourcedestination의 객체 타입이나 프로퍼티가 다른 경우에도 설정된 매칭 전략에 따라 최선의 매핑 과정을 수행한다.

 

하지만 위처럼 암시적으로 일치하는 프로퍼티들의 연관관계가 존재하지 않거나, 이런 연관관계가 모호한 경우 매핑이 원활히 이루어지지 않을 수 있다. 다양한 설정 방법들로 모호한 연관관계를 매핑할 수 있는 방법들을 살펴보자

 

TypeMap

/* 모든 클래스 Constructor, Getter, Setter 생략 */

public class Item {
    private String name;
    private Integer stock;
    private Integer price;
    private Double discount;
}
class Bill {
    private String itemName;
    private Integer qty;
    private Integer singlePrice;
    private Boolean sale;
}
Item itemA = new Item("itemA", 10, 1500, true);
Bill bill = modelMapper.map(itemA, Bill.class);
  • 실행 결과
result = {
	itemName = "itemA"
	qty = null
	singlePrice = null
	discount = null
}

ModelMapper의 기본 매칭 전략으로는 모호한 연관 관계들은 매핑되지 않는다.

이러한 문제를 해결하기 위해 TypeMap 기능을 제공한다

 

TypeMap<S, D>

TypeMap 인터페이스를 구현함으로 매핑 설정을 캡슐화(Encapsulating)하여 ModelMapper 객체의 매핑 관계를 설정해 줄 수 있다.

 

매핑 관계 추가

위 예제의 우리가 원하는 매핑 전략은 다음과 같다

  • Item.stock → Bill.qty
  • Item.price → Bill.singlePrice
  • Item.sale → Bill.discount

타입이 동일한 수량가격의 경우 다음과 같이 설정할 수 있다

modelMapper.typeMap(Item.class, Bill.class).addMappings(mapper -> {
        mapper.map(Item::getStock, Bill::setQty);
        mapper.map(Item::getPrice, Bill::setSinglePrice);
    });

Bill bill2 = modelMapper.map(itemA, Bill.class);
  • 실행 결과
result = {
	itemName = "itemA"
	qty = 10
	singlePrice = 1500
	discount = null
}

임의로 커스터마이징한 매핑 관계가 정상적으로 적용되었다.

 

 

하지만 Item.sale , Bill.discount와 같이 클래스 타입이 다른 경우는 추가적인 방법이 필요하다.

 

파라미터 타입 변환

매핑하려는 데이터의 sourcedestination 타입이 다른 경우, Converter 인터페이스를 사용하여 유연하게 값을 설정해 줄 수 있다.

modelMapper.typeMap(Item.class, Bill.class).addMappings(mapper -> {
        mapper.map(Item::getStock, Bill::setQty);
        mapper.map(Item::getPrice, Bill::setSinglePrice);
        mapper.using((Converter<Boolean, Double>) context -> context.getSource() ? 20.0 : 0.0)
                .map(Item::isSale, Bill::setDiscount);
    });

Bill bill2 = modelMapper.map(request, Bill.class);

Item.sale == true 인 경우 할인율을 20.0 으로 설정해준다고 가정했을 때, mapper.using(Converter<S, D>) 와 같은 패턴을 이용하면 유연한 타입 변환이 가능하다.

using은 말 그대로 Converter 규칙을 사용하겠다는 것이다.

  • 실행 결과
result = {
	itemName = "itemA"
	qty = 10
	singlePrice = 1500
	discount = 20.0
}

 

Skip

또한 클래스의 특정 프로퍼티는 매핑이 이루어지지 않도록 설정하는 것도 가능하다

modelMapper.typeMap(Item.class, Bill.class).addMappings(mapper -> {
        mapper.map(Item::getStock, Bill::setQty);
        mapper.map(Item::getPrice, Bill::setSinglePrice);
        mapper.using((Converter<Boolean, Double>) context -> context.getSource() ? 20.0 : 0.0)
                .map(Item::isSale, Bill::setDiscount);
        mapper.skip(Bill::setItemName); // skip 추가
    });
Bill bill2 = modelMapper.map(itemA, Bill.class);
  • 실행 결과
result = {
	itemName = null
	qty = 10
	singlePrice = 1500
	discount = 20.0
}

null인 속성 값만 Skip 하기

객체에 새로운 값들을 한번에 업데이트할 때, ModelMapper 기본 매칭 전략을 사용하면 null 값까지 함께 업데이트 되는 문제가 생기므로 이를 위해서 매핑 설정을 해줄 수 있다.

ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setSkipNullEnabled(true);

 

Validation

ModelMapper 는 기본적으로 매칭 전략에 맞지 않는 속성들은 null 값으로 초기화하게 되는데 개발자의 입장에서는 어떤 객체에 대해 모든 속성값들이 정상적으로 매핑되었는지 검증이 필요할 때가 있다.

이때는 ModelMapper().validate() 를 이용하여 매핑 검증이 실패하는 경우 예외 처리를 해주기 때문에 추가적인 예외 핸들링이 가능하다.

modelMapper = new ModelMapper();
Bill bill3 = modelMapper.map(itemA, Bill.class);
try {
    modelMapper.validate();
} catch (ValidationException e) {
    /* Exception Handling */
}

 

Strategies

앞에서 설정한 여러 가지 조건들에 의해 ModelMapper 는 지능적인 오브젝트 매핑을 수행한다.

하지만 객체들의 매칭 전략을 하나하나씩 임의로 설정해 주어야 한다면 편의성을 위해서 ModelMapper 라이브러리를 사용하는 것이 아니게 되므로.. 특정 매칭 전략을 입력해 주지 않고도 다른 매칭 전략을 사용할 수 있게끔 추가적인 매칭 전략을 제공한다.

modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STANDARD) // STANDARD 전략
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.LOOSE) // LOOSE 전략
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT) // STRICT 전략

 STANDARD

기본 매칭 전략으로, sourcedestination의 속성들을 지능적으로 매치시킬 수 있다

  • 토큰은 어떤 순서로든 일치될 수 있다
  • 모든 destination 속성 이름 토큰이 일치해야 한다
  • 모든 source 속성 이름은 일치하는 토큰이 하나 이상 있어야 한다.

위 조건을 충족하지 못하는 경우 매칭에 실패하게 된다. (Null)

 

 LOOSE

느슨한 매칭 전략으로, 계층 구조의 마지막 destination 속성만 일치하도록 요구한다

  • 토큰은 어떤 순서로든 일치될 수 있다
  • 마지막 destination 속성 이름에는 모든 토큰이 일치해야 한다
  • 마지막 source 속성 이름은 일치하는 토큰이 하나 이상 있어야 한다

느슨한 매칭 전략은 속성 계층 구조가 매우 다른 source, destination 객체에 사용하는 데 이상적이다

e.g. 처음 예제의 Order, OrderDtd 와 같이 객체의 속성이 계층 구조를 가지는 경우

 

 STRICT

엄격한 일치 전략으로, source 속성을 destination 속성과 엄격하게 일치시킬 수 있다. 따라서 불일치나 모호성이 발생하지 않도록 완벽한 일치 정확도를 얻을 수 있다. 하지만 각 속성 이름들이 서로 정확하게 일치해야한다.

  • 토큰들은 엄격한 순서로 일치해야 한다
  • 모든 destination 속성 이름 토큰이 일치해야 한다
  • 모든 source 속성 이름에는 모든 토큰이 일치해야 한다

 

 


참고

http://modelmapper.org/getting-started/#how-it-works

https://devwithpug.github.io/java/java-modelmapper/

 

 

728x90
반응형

댓글

추천 글