如何在Java中从现有的DTO创建一个轻量级DTO?

huangapple go评论134阅读模式
英文:

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:

	&lt;dependency&gt;
	    &lt;groupId&gt;org.modelmapper&lt;/groupId&gt;
	    &lt;artifactId&gt;modelmapper&lt;/artifactId&gt;
	    &lt;version&gt;2.3.2&lt;/version&gt;
	&lt;/dependency&gt;

You necessarily need another DTO in "lite" version. You can't do otherwise, I think.

huangapple
  • 本文由 发表于 2020年5月4日 19:03:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/61590717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定