4

I have the following domain structure:

abstract class Person { String name; //with getter and setter }
class Employer extends Person {}
class Employee extends Person {}
class Contract { Person contractor; //with getter and setter }
class PersonDTO implements Serializable { String name; String type; //type == 'Employee' or 'Employer' }
class ContractDTO implements Serializable { PersonDTO contractor; }

Now when I set up this following dozer mapping:

<mapping>
   <class-a>Person</class-a>
   <class-b>PersonDTO</class-b>
</mapping>
<mapping>
   <class-a>Employer</class-a>
   <class-b>PersonDTO</class-b>
</mapping>
<mapping>
   <class-a>Contract</class-a>
   <class-b>ContractDTO</class-b>
</mapping>

My problem concerns the mapping of the field Contract.contractor from B to A because the field Contract.contractor is an abstract class and dozer cannot guess how to instanciate it.

So my question is simple: how can I indicate to dozer that, for the mapping of the field Contract.contractor, it should instantiate an instance of Employer if type == 'Employer' and elsewhere Employee ?

Thank you for your help.

fabien7474
  • 16,300
  • 22
  • 96
  • 124
  • Your Person class is abstract but I guess it has to be an instance of any of the inherited classes at runtime? How is the contractor attribute created for the source object? – Gonzalo Garcia Lasurtegui Dec 12 '11 at 10:40
  • @Gonzalo I don't understand your question. contractor is either an Employer or an Employee and it is set thourgh the method setContractor(Person contractor) – fabien7474 Dec 12 '11 at 11:17
  • That's correct, at runtime, Person is either one of those two types you mention, and Dozer should be able to figure that out and convert the concrete type correctly. Dozer will not attempt to create an instance of the abstract class, but of the actual object that contractor references at runtime (eith Employer or Employee). What sort of errors are you getting? – Gonzalo Garcia Lasurtegui Dec 12 '11 at 11:24
  • @Gonzalo I have updated the question to make it clear. Now, PersonDTO has an attribute 'type' which clearly indicates the type of Person (Employee or Employer). How can I tell Dozer to instanciate an Employer if type == 'Employer' ? – fabien7474 Dec 12 '11 at 14:41
  • I think you need a custom converter for this type of logic. http://dozer.sourceforge.net/documentation/customconverter.html With a custom converter you can implement whichever logic you want to define the output of the conversion process – Gonzalo Garcia Lasurtegui Dec 12 '11 at 14:45

1 Answers1

0

You can do this with hints. Somewhat like this:

<mapping>
 <class-a>Contract</class-a>
 <class-b>ContractDTO</class-b>
 <field>
   <a>contractor</a>
   <b>contractor</b>
   <a-hint>your.package.Employer, your.package.Employee</a-hint>
   <b-hint>your.DTOpackage.EmployerDTO, your.DTOpackage.EmployeeDTO</b-hint>
 </field>
</mapping>
K.C.
  • 2,084
  • 2
  • 25
  • 38