推土机升级到mapstruct

问题描述 投票:1回答:1

我在我的应用程序中使用dozer进行bean到bean映射...由于它的漏洞,我想升级到mapstruct

在dozer中,我们有一个映射器函数用于bean到bean的映射,它为所有不同的实例进行映射。

在MapStruct中,我无法使用相同的方法实现。

import java.util.Map;
import org.dozer.DozerBeanMapper;
import org.dozer.MappingException;

/**
 * Factory for creating DTO objects based on the object identifier that
 * is passed to the object creation method.
 */
public class RetrieveChangeSetObjectDtoFactory {
    private Map<String, String> objectIdentifiers;  
    private DozerBeanMapper beanMapper;

    public Object createDto(String objectIdentifier, Persistence srcObject) throws MappingException, ClassNotFoundException {
        String className = objectIdentifiers.get(objectIdentifier);

        if (className == null) {
            return null;
        }

        return beanMapper.map(srcObject, Class.forName(className));
    }

    /**
     * Setter for the object identifiers map, maps the domain objects to their associated DTO classes.
     * 
     * @param objectIdentifiers object identifiers map
     */
    public void setObjectIdentifiers(Map<String, String> objectIdentifiers) {
        this.objectIdentifiers = objectIdentifiers;
    }

    /**
     * Setter for the bean mapper.
     * 
     * @param beanMapper bean mapper (dozer)
     */
    public void setBeanMapper(DozerBeanMapper beanMapper) {
        this.beanMapper = beanMapper;
    }
}

beanmapper.map为我映射对象...通过hashmap spring bean加载映射的对象

希望有一个相同的方法来映射存储在hashmap中的所有对象

enter image description here

这是我的Spring Dozer bean

java dozer mapstruct
1个回答
0
投票

MapStruct和Dozer之间的一个重要区别是MapStruct是一个注释处理器工具,这意味着它生成代码。您将必须创建将生成所需映射代码的接口/映射。

MapStruct没有执行通用映射的单个入口点。但是,如果您愿意,可以在自己的方面实现类似的功能。

您需要一个所有映射器都将实现的基本接口

public interface BaseMapper<S, T> {

    T toDto(S source);

    S toEntity(T target);
}

然后,您需要以稍微不同的方式实现RetrieveChangeSetObjectDtoFactory

public class RetrieveChangeSetObjectDtoFactory {

    private Map<Class<?>, Map<Class<?>, BaseMapper<?, ?>>> entityDtoMappers = new HashMap<>();

    public <S, T> Object createDto(Class<S> entityClass, Class<T> dtoClass, S source) {
        if (source == null) {
            return null;
        }

        return getMapper(entityClass, dtoClass).toDto(source);
    }

    public <S, T> Object createSource(Class<S> entityClass, Class<T> dtoClass, T dto) {
        if (dto == null) {
            return null;
        }

        return getMapper(entityClass, dtoClass).toEntity(dto);
    }

    @SuppressWarnings("unchecked")
    protected <S, T> BaseMapper<S, T> getMapper(Class<S> entityClass, Class<T> dtoClass) {
        // appropriate checks
        return (BaseMapper<S, T>) entityDtoMappers.get(entityClass).get(dtoClass);
    }

    public <S, T> void registerMapper(Class<S> entityClass, Class<T> dtoClass, BaseMapper<S, T> mapper) {
        entityDtoMappers.computeIfAbsent(entityClass, key -> new HashMap<>()).put(dtoClass, mapper);
    }
}

但是,我建议只注入你需要它们的映射器而不是做一些通用的东西。

© www.soinside.com 2019 - 2024. All rights reserved.