简体   繁体   English

从 HashMap 获取值并填充 Java 对象

[英]Get Values from HashMap and Populate a Java Object

I have map populated from database Data.我已经从数据库数据填充了地图。 I need to get values from there to Object.我需要从那里获取值到对象。 Field names in POJO and key names in Map object are different. POJO 中的字段名和 Map 对象中的键名不同。 I did it as the below.我做了如下。 is there any effective way to do this有什么有效的方法可以做到这一点

 Map<String ,Object> map; //retrieved from database

Employee e = new Employee();
if(map!=null) {
    if(map.containsKey("name")) {
        e.setFirstName(map.get("name"));
    }
    if(map.containsKey("ads")) {
        e.setMyAddress(map.get("ads"));
    }
    if(map.containsKey("country")) {
        e.setDealCountry(map.get("country"));
    }
    if(map.containsKey("keyId")) {
        e.Id(map.get("keyId"));
    }
}



public class Employee {
    String firstName;
    String id;
    String myAdreess;
    String dealCountry;
//setter getters
}

You can take a look to Hibernate or other ORM's.您可以查看 Hibernate 或其他 ORM。 They automatically do the mapping for you.他们会自动为您进行映射。

Here for example a link to the Hibernate ORM: https://hibernate.org/例如,这里有一个指向 Hibernate ORM 的链接: https : //hibernate.org/

It's easier and faster than make the mapping manuelly.这比手动进行映射更容易、更快。 ;) ;)

You can use java8+'s BiConsumer to define a setter for each of the map's keys:您可以使用 java8+ 的 BiConsumer 为地图的每个键定义一个 setter:

    Map<String, BiConsumer<Employee, String>> consumerMap = new HashMap<>();
    consumerMap.put("name", Employee::setFirstName);
    consumerMap.put("ads", Employee::setMyAddress);
    consumerMap.put("country", Employee::setDealCountry);
    //and so on

    Map<String, String> map = new HashMap<>();//the data from your database 
    Employee e = new Employee();
    if (map != null) {
        consumerMap.forEach((key, value) -> {
            if (map.containsKey(key)) {
                //value is the BiConsumer
                value.accept(e, map.get(key));
            }
        });
    }

The forEach iterates over all the the defined mappings, then checks if your Map from the database has the respective keys and applies the data. forEach 迭代所有定义的映射,然后检查您的数据库中的Map是否具有相应的键并应用数据。

This does not involve any (manual) reflection and the mapping from the map's key to the setter is very direct.这不涉及任何(手动)反射,并且从映射键到 setter 的映射非常直接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM