高效的将数据从Map映射到DTO/VO对象的方法

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

Efficient Way of Mapping data from Map to DTO/VO Object

问题

以下是翻译好的部分:

我有一个包含值的映射(Map),我想将这些值映射到DTO(数据传输对象)。

与其使用 if else 条件并映射到 DTO 对象,是否有更好的方法来做这件事呢?

这是我的代码:

public class Test {
    public static void main(String[] args) {
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("empName", "Pavan");
        hashMap.put("deptNO", "12");
        hashMap.put("country", "IND");
        hashMap.put("age", "34");

        // TODO Auto-generated method stub
        Set<String> keys = hashMap.keySet();
        for(String key: keys){
            Employee emp = new Employee();
            if(key.equals("empName"))
                emp.setName(hashMap.get("empName"));
        }
    }
}

public class Employee {
    
    private String empName ;
    private String deptNO ;
    private String country ;
    private String age ;
    
    // setters and getters
}

我知道传统的做法是:

for(String key: keys){
    Employee emp = new Employee();
    if(key.equals("empName"))
        emp.setName(hashMap.get("empName"));
}

是否有更好的方法来做这个?

英文:

I have a Map with values and i want to map this values to a DTO

Rather than using if else conditions and mapping to DTO Object , is there any better way of doing so

This is my code

public class Test {
	public static void main(String[] args) {
		HashMap&lt;String , Object&gt; hashMap = new HashMap&lt;String , Object&gt;();
		hashMap.put(&quot;empName&quot;, &quot;Pavan&quot;);
		hashMap.put(&quot;deptNO&quot;, &quot;12&quot;);
		hashMap.put(&quot;country&quot;, &quot;IND&quot;);
		hashMap.put(&quot;age&quot;, &quot;34&quot;);
		
		// TODO Auto-generated method stub
		Set&lt;String&gt; keys = hashMap.keySet();
        for(String key: keys){
        	Employee emp = new Employee();
        	if(key.equals(&quot;empName&quot;))
        	emp.setName(hashMap.get(&quot;empName&quot;))
        }
	}
}

public class Employee {
	
	private String empName ;
	private String deptNO ;
	private String country ;
	private String age ;
	
	// setters and getters
}

I know the tradational way of doing as

for(String key: keys){
  Employee emp = new Employee();
  if(key.equals(&quot;empName&quot;))
     emp.setName(hashMap.get(&quot;empName&quot;))
}

Is there any better way of doing this ?

答案1

得分: 1

你可以使用BeanUtils.populate将你的HashMap的键复制到一个Java Bean中,以下是一个示例:

import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;

public class Test {

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {

        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("empName", "Pavan");
        hashMap.put("deptNO", "12");
        hashMap.put("country", "IND");
        hashMap.put("age", "34");
        EmployeeDTO employeeDTO = new EmployeeDTO();
        BeanUtils.populate(employeeDTO, hashMap);
        System.out.println(employeeDTO);

    }

}

输出

EmployeeDTO{empName='Pavan', deptNO='12', country='IND', age='34'}

了解更多信息:

英文:

You can use the BeanUtils.populate to copy your HashMap keys to a bean, here's an example:

import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;

public class Test {
    
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {

        HashMap&lt;String , Object&gt; hashMap = new HashMap&lt;String , Object&gt;();
        hashMap.put(&quot;empName&quot;, &quot;Pavan&quot;);
        hashMap.put(&quot;deptNO&quot;, &quot;12&quot;);
        hashMap.put(&quot;country&quot;, &quot;IND&quot;);
        hashMap.put(&quot;age&quot;, &quot;34&quot;);
        EmployeeDTO employeeDTO = new EmployeeDTO();
        BeanUtils.populate(employeeDTO,hashMap);
        System.out.println(employeeDTO);

    }

}

Output

EmployeeDTO{empName=&#39;Pavan&#39;, deptNO=&#39;12&#39;, country=&#39;IND&#39;, age=&#39;34&#39;}

Read more here:

答案2

得分: 0

你可以为Employee类创建一个带参数的构造函数:

public class Employee {

    private String empName;
    private String deptNO;
    private String country;
    private String age;

    Employee(String empName, String deptNO, String country, String age){
       this.empName = empName;
       this.deptNO = deptNO;
       this.country = country;
       this.age = age;
    }
}

并且你可以从Map中创建Employee对象:

public class Test {
    public static void main(String[] args) {
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
        hashMap.put("empName", "Pavan");
        hashMap.put("deptNO", "12");
        hashMap.put("country", "IND");
        hashMap.put("age", "34");

        Employee emp = new Employee((String) hashMap.get("empName"), (String) hashMap.get("deptNO"), (String) hashMap.get("country"), (String) hashMap.get("age"));
    }
}

如果你在Map中有许多字段,你可以在Employee类中使用HashMap来获取现有的属性:

public class Employee {
    private HashMap<String, Object> hashMap;

    Employee(HashMap<String, Object> hashMap){
       this.hashMap = hashMap;
    }

    public Object getProperty(String propertyName){
       return hashMap.get(propertyName);
    }
}
英文:

You can have a parameterized constructor for Employee class

public class Employee {
    
    private String empName;
    private String deptNO;
    private String country;
    private String age;
    
    Employee(String empName, String deptNO, String country, String age){
       this.empName = empName;
       this.deptNO = deptNO;
       this.country = country;
       this.age = age;
    }
}

and you can create Employee object from map.

public class Test {
    public static void main(String[] args) {
        HashMap&lt;String , Object&gt; hashMap = new HashMap&lt;String , Object&gt;();
        hashMap.put(&quot;empName&quot;, &quot;Pavan&quot;);
        hashMap.put(&quot;deptNO&quot;, &quot;12&quot;);
        hashMap.put(&quot;country&quot;, &quot;IND&quot;);
        hashMap.put(&quot;age&quot;, &quot;34&quot;);
        
        Employee emp = new Employee(hashMap.get(&quot;empName&quot;), hashMap.get(&quot;deptNO&quot;), hashMap.get(&quot;country&quot;), hashMap.get(&quot;age&quot;));
    }
}

EDIT: If you have many fields in map, you can use hashmap in Employee class to get the existing properties.

public class Employee {
    private HashMap&lt;String, Object&gt; hashMap;
    
    Employee(HashMap&lt;String, Object&gt; hashMap){
       this.hashMap = hashMap;
    }

    public Object getProperty(String propertyName){
       return hashMap.get(propertyName);
    }
}

答案3

得分: 0

使用 MapStruct 的方法 -

定义了一个名为 EmployeeMapper 的接口

@Mapper
public interface EmployeeMapper {

  EmployeeMapper MAPPER = Mappers.getMapper(EmployeeMapper.class);

  @Mapping(expression = "java(parameters.get(\"empName\"))", target = "empName")
  @Mapping(expression = "java(parameters.get(\"deptNO\"))", target = "deptNO")
  @Mapping(expression = "java(parameters.get(\"country\"))", target = "country")
  @Mapping(expression = "java(parameters.get(\"age\"))", target = "age")
  Employee map(final Map<String, String> parameters);
}

在你的代码中调用 -

Employee employee = EmployeeMapper.MAPPER.map(hashMap);

这种方法并不像你希望的那样简洁,但它能完成任务。另一种方法是使用 Qualifier,在这里有描述 链接Qualifier 方法冗长,并且它并不能完全解决你的问题,因为你仍然需要为每个字段定义映射。

MapStruct 目前不完全支持从 Map 进行转换,有一个 特性请求 和一个待定的 PR

英文:

Approach using MapStruct -

Defined an interface EmployeeMapper

@Mapper
public interface EmployeeMapper {

  EmployeeMapper MAPPER = Mappers.getMapper(EmployeeMapper.class);

  @Mapping(expression = &quot;java(parameters.get(\&quot;empName\&quot;))&quot;, target = &quot;empName&quot;)
  @Mapping(expression = &quot;java(parameters.get(\&quot;deptNO\&quot;))&quot;, target = &quot;deptNO&quot;)
  @Mapping(expression = &quot;java(parameters.get(\&quot;country\&quot;))&quot;, target = &quot;country&quot;)
  @Mapping(expression = &quot;java(parameters.get(\&quot;age\&quot;))&quot;, target = &quot;age&quot;)
  Employee map(final Map&lt;String, String&gt; parameters);
}

and in your code call as -

Employee employee = EmployeeMapper.MAPPER.map(hashMap);

This is not as concise as you want but it does the work. Another approach is to use Qualifier, as described here. Qualifier approach is verbose and it doesn't solve your problem entirely as you still need to define mapping for each field.

MapStruct currently doesn't have full support for conversion from Map and there is a feature request and PR pending for long.

huangapple
  • 本文由 发表于 2020年8月22日 20:51:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63536387.html
匿名

发表评论

匿名网友

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

确定