mapstruct / mapstruct-examples

Examples for using MapStruct
Other
1.28k stars 511 forks source link

MapStruct Map to Bean with reference fields not working #126

Closed Manojred1236 closed 2 years ago

Manojred1236 commented 2 years ago

I have a requirement to convert Map to bean using MapStruct

Employee.java public class Employee{ private String id; private String name; private Department department }

Department.java public class Employee{ private String id; private String name; }

I want to convert below map to Employee instance

Map<String,String> map = new HashMap(); map.put("id", "1234"); map.put("name", "Mark"); map.put("did", "32222"); //Department Id map.put("dname", "Test");// Depart name

How can we convert above map to Employee. How to set the fields of Department in Employee instance?

Can someone Please hep how to solve the above issue. Is there a support for the above scenario in MapStruct latest versions?

filiphr commented 2 years ago

@Manojred1236 we've added an example for your use case in https://github.com/mapstruct/mapstruct-examples/commit/37dd4c26a84e31dba3f3213fb434e7c14af1c49c.

In theory

    @Mapping(target = "department.id", source = "did")
    @Mapping(target = "department.name", source = "dname")
    Employee fromMap(Map<String, String> map);

should also work. However, it seems it is not working as it should.