英文:
How to create a lite DTO from existing DTO in java?
问题
我有一个数据传输对象(DTO),叫做MyDto
,其中有10个字段。我想要创建一个只有3个字段的DTO轻量版本。
我尝试了这样做:创建了一个新对象,并将旧对象中所需的字段复制到新对象中,然后将其他字段设置为null。
我不太想创建一个只有3个字段的新轻量级DTO。我可以采取哪些方法呢?
英文:
I have a dto, say MyDto
having 10 fields in it. I want to create a light version of that dto with 3 fields only.
I tried this: Created a new object and copy required fields from old object to new object, and set other fields to null.
I do not prefer to make a new light dto with 3 fields only. What are the approaches I can follow here?
答案1
得分: 1
我也遇到了同样的问题。在我的情况下,我是这样使用 ModelMapper 的。
在需要映射的类中:
@Autowired
private ModelMapper modelMapper;
...
public LiteDTO convertToLiteDTO() {
MyDTO myDTO = new MyDTO();
return modelMapper.map(myDTO, LiteDTO.class);
}
而且,在应用程序中配置 ModelMapper:
// MyBEConfig.java
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
...
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
使用 Maven 安装 ModelMapper:
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.2</version>
</dependency>
你必须在“lite”版本中需要另一个 DTO。我认为你没有其他选择。
英文:
I've had the same problem. In my case I used ModelMapper in this way.
In the class that needs mapping:
@Autowired private ModelMapper modelMapper;
...
public LiteDTO convertToLiteDTO() {
MyDTO myDTO = new MyDTO();
return modelMapper.map(myDTO, LiteDTO.class);
}
And, to configure ModelMapper in the application:
// MyBEConfig.java
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
...
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
To install ModelMapper with Maven:
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.2</version>
</dependency>
You necessarily need another DTO in "lite" version. You can't do otherwise, I think.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论