如何将DTO映射到现有的JPA实体? [英] How to map a DTO to an existing JPA entity?
问题描述
我试图将Java DTO对象映射到现有的JPA实体对象,而不必执行以下操作:
I'm trying to map a Java DTO object to an existing JPA entity object without having to do something like the following:
public MyEntity mapToMyEntity(SomeDTO dto, MyEntity entity) {
entity.setField1(dto.getField1());
entity.setField2(dto.getField2());
...
entity.setField20(dto.getField20());
return entity;
}
到目前为止,我一直在使用 ModelMapper ,例如:MyEntity entity = modelMapper.map(dto, SomeDTO.class);
,但是我正在尝试而是映射到现有实体对象,而不是从DTO创建 new 实体对象.我浏览了ModelMapper手册,没有创建新对象就找不到如何映射的方法.我是否坚持为每个我可能拥有的每个实体对象手动添加每个成员变量?
Up to now I've been using ModelMapper like so: MyEntity entity = modelMapper.map(dto, SomeDTO.class);
, but what I'm trying to do instead is map to an existing entity object rather than creating a new entity object from a DTO. I've looked through the ModelMapper manual and couldn't find how to map without creating a new object. Am I stuck adding each member variable manually for each entity object I might have?
推荐答案
您可以使用推土机映射器或gson.
You can use dozer mapper or gson.
DozerMapper例如:
DozerMapper ex:
Mapper mapper = DozerBeanMapperBuilder.createDefault();
DestinationObject destObject = mapper.map(sourceObject,DestinationClassName.class);
您可以查看 github页面以获取更多信息
You can check github page for more information
这篇关于如何将DTO映射到现有的JPA实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!