gpt4 book ai didi

java - 推土机升级到mapstruct

转载 作者:太空宇宙 更新时间:2023-11-04 10:23:58 25 4
gpt4 key购买 nike

我正在使用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

最佳答案

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

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

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

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);
}
}

但是,我建议只注入(inject)您需要的映射器,而不是做一些通用的事情。

关于java - 推土机升级到mapstruct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50772340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com