Wednesday 2 March 2022

Dozer: bean mapping: hello world application

In this post, I am going to explain a simple example, where source and destination objects have same properties.

 

In Dozer, Matched property names are automatically handled by Dozer. Two properties with different names can be mapped either progamatically or via xml configuration.

 

Example

<field>
  <a>fName</a>
  <b>firstName</b>
</field>

 

Field ‘fName’ in type ‘a’ is mapped to the field ‘firstName’ in type ‘b’.

 

Step 1: Define Type1.

 

public class Type1 {
	private int a;
	private int b;

	......
	......
}

 

Step 2: Define Type2.

public class Type2 {
	private int a;
	private int b;

	......
	......
}

 

Step 3: Map Type1 data to Type2 object.

DozerBeanMapper mapper = new DozerBeanMapper();
Type1 type1 = new Type1(10, 20);
Type2 type2 = mapper.map(type1, Type2.class);


 

Find the below working application.

 

Type1.java

package com.sample.app.model;

public class Type1 {
	private int a;
	private int b;

	public Type1() {
	}

	public Type1(int a, int b) {
		this.a = a;
		this.b = b;
	}

	public int getA() {
		return a;
	}

	public void setA(int a) {
		this.a = a;
	}

	public int getB() {
		return b;
	}

	public void setB(int b) {
		this.b = b;
	}

	@Override
	public String toString() {
		return "Type1 [a=" + a + ", b=" + b + "]";
	}

}

 

Type2.java

package com.sample.app.model;

public class Type2 {
	private int a;
	private int b;

	public Type2() {
	}

	public Type2(int a, int b) {
		this.a = a;
		this.b = b;
	}

	public int getA() {
		return a;
	}

	public void setA(int a) {
		this.a = a;
	}

	public int getB() {
		return b;
	}

	public void setB(int b) {
		this.b = b;
	}

	@Override
	public String toString() {
		return "Type2 [a=" + a + ", b=" + b + "]";
	}

}

 

HelloWorld.java

package com.sample.app;

import org.dozer.DozerBeanMapper;

import com.sample.app.model.Type1;
import com.sample.app.model.Type2;

public class HelloWorld {

	public static void main(String[] args) {
		DozerBeanMapper mapper = new DozerBeanMapper();

		Type1 type1 = new Type1(10, 20);
		Type2 type2 = mapper.map(type1, Type2.class);
		
		System.out.println(type1);
		System.out.println(type2);
	}

}

 

Output

Type1 [a=10, b=20]
Type2 [a=10, b=20]

 

 

 

 

 

 

 

 

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment