Bidirectional Mapping

125 views
Skip to first unread message

Farouk Elabady

unread,
Jan 17, 2016, 9:33:01 AM1/17/16
to JMapper Framework
Hello, 

I am trying the following scenario to map two sources (department , employee) to (destinationDepartment, destinationEmployee), with bidirectional relation between the two,
as shown in the below code

public class DepSource {
 
 
private String name;
 
 
private EmpSource employee;
       
// getters and setters
}



public class EmpSource {
 
 
private String name;
 
 
private DepSource department;
     
// getters and setters
}




public class DepDest {
 
 
@JMap
 
String name;
 
 
@JMap("employee")
 
EmpDest emp;


// getters and setters


}


public class EmpDest {
 
 
@JMap
 
String name;
 
 
@JMap(value = "department")
 
DepDest dep;


// getters and setters
}




 public static void main(String[] args) {
 
DepSource depSource = new DepSource();
 depSource
.setName("Department 1");
 
EmpSource empSource = new EmpSource();
 empSource
.setName("employee 1");
 depSource
.setEmployee(empSource);
 empSource
.setDepartment(depSource);
 
JMapper<EmpDest, EmpSource> mapper = new JMapper<>(EmpDest.class, EmpSource.class);
 
EmpDest des = mapper.getDestination(empSource,MappingType.ONLY_NULL_FIELDS);
 
System.out.println(des.getName());
 
System.out.println(" : " + des.getDep().getName());
 
System.out.println(" : " + des.getDep().getEmp().getName());
 
}



when trying to run the code , it gives stack overflow exception, so what is the correct way of doing such mapping 
Note: what I am trying to to do is to mimic the bidirectional relation like what can be found in JPA entities

Best regards
Farouk Elabady

Alessandro Vurro

unread,
Jan 17, 2016, 1:29:40 PM1/17/16
to JMapper Framework
Hi Farouk,

this is a case of infinite recursive mapping, EmpSource contains DepSource and viceversa, equal for other classes.
JMapper does not know when to stop mapping, the only solution is to stop the recursion.

I hope to be a help

Farouk Elabady

unread,
Jan 31, 2016, 7:21:01 AM1/31/16
to JMapper Framework
Hi Alessandro,

That is true, I managed though to stop the infinte recursive mapping using @JmapConversion method and mapping the object inside the method,
although the method is trivial, but I think it will be good if I can control the depth of the mapping to prevent infinite loop, 
also it will be much needed if for example there is tree of objects, and I want to just mad the first or second level of the tree, 
e.g @JMap(depth = 1)

and thanks for your help :)
Reply all
Reply to author
Forward
0 new messages