Skip to content

Instantly share code, notes, and snippets.

@ghsatpute
Created May 15, 2020 18:39
Show Gist options
  • Save ghsatpute/bb3755718dec8a6df63c332ce8fa9483 to your computer and use it in GitHub Desktop.
Save ghsatpute/bb3755718dec8a6df63c332ce8fa9483 to your computer and use it in GitHub Desktop.
Spring Boot Mapper Example
...
import ma.glasnost.orika.CustomMapper;
import ma.glasnost.orika.Mapper;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.impl.ConfigurableMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
/*
* Created by Ganesh Satpute on 17/7/18 6:16 PM.
*/
@Component
public class UserMapper extends ConfigurableMapper {
@Autowired
private UserAddressMapper userAddressMapper = null;
@Override
protected void configure(MapperFactory mapperFactory) {
mapperFactory
.classMap(UserDTO.class, UserEntity.class)
.exclude("id")
.byDefault()
.customize(getCustomizedMapper())
.register();
}
private Mapper<UserDTO, UserEntity> getCustomizedMapper() {
return new CustomMapper<UserDTO, UserEntity>() {
@Override
public void mapAtoB(UserDTO userDTO, userEntity userEntity,
MappingContext context) {
if (CollectionUtils.isEmpty(userDTO.getAddresses())) {
List<EnvironmentOutputEntity> addresses =
environmentOutputsMapper.mapAsList(userEntity.getAddresses(),
UserAddressEntity.class);
userEntity.setAddresses(addresses);
}
}
@Override
public void mapBtoA(userEntity userEntity, UserDTO userDTO,
MappingContext context) {
if (!CollectionUtils.isEmpty(userEntity.getOutputs())) {
List<UserAddressDTO> addresses =
userAddressMapper.mapAsList(userEntity.getAddresses(), userAddressDTO.class);
userDTO.setAddresses(addresses);
}
userDTO.setId(userEntity.getId().toString());
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment