Sunday 18 July 2021

Dozer Mapping

Dozer is a Java Bean to Java Bean mapper that recursively copies data from one object to another. Typically, these Java Beans will be of different complex types.


Dozer supports simple property mapping, complex type mapping, bi-directional mapping, implicit-explicit mapping, as well as recursive mapping. This includes mapping collection attributes that also need mapping at the element level.


We can see the implementation of the dozer in this post. This way is not recommended since the update is not coming from the developer's side.


Here the Mapping is very easy.


Just add the maven dependency. then identify the source and destination classes. The add the mapping in the source class then this will automatically convert the object.


Consider the below example.


Maven dependency.


             <dependency>

<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.5.1</version>

</dependency>


Source Object:


package com.greet.user;


import org.dozer.Mapping;


public class MessagePojo {

@Mapping("welcomeMessage")

String message;


public String getMessage() {

return message;

}


public void setMessage(String message) {

this.message = message;

}


public MessagePojo() {

}


}



Destination Object:


package com.greet.user;


public class GreetingPojo {

String welcomeMessage;

public GreetingPojo() {

super();

// TODO Auto-generated constructor stub

}


public GreetingPojo(String welcomeMessage, String greetings) {

super();

this.welcomeMessage = welcomeMessage;

this.greetings = greetings;

}


public String getWelcomeMessage() {

return welcomeMessage;

}


public void setWelcomeMessage(String welcomeMessage) {

this.welcomeMessage = welcomeMessage;

}


public String getGreetings() {

return greetings;

}


public void setGreetings(String greetings) {

this.greetings = greetings;

}


String greetings;


}


Here the Message Object in Message Pojo needs to be mapped to the GreetingPojo welcomeMessage. Hence I have used the mapping in the message POJO with the field name.


Then In the class where we are converting needs the below code.


Mapping:


MessagePojo msg = new MessagePojo();

msg.setMessage("Greetings from Spring Boot!");

GreetingPojo targetObj = new DozerBeanMapper().map(msg, GreetingPojo.class);


where msg is the source object and GreetingPojo class. This converts the messagePojo to the GreetigPojo. 


Happy Learning!!!!

No comments:
Write comments