Tuesday 3 August 2021

Modelmapper: Hello World application

In this post, I am going to explain how to map an object of source type to the object of destination type. Modelmapper maps based on property names in source and target objects by default (You can specify custom mappings if required).

 

Step 1: Define Person class.

public class Person {

	private int id;
	private String name;
	.....
	.....
	.....
}

 

Step 2: Define PersonDto class.

public class PersonDto {
	private int id;
	private String name;
	......
	......
}

 

Step 3: Map the Person object to PersonDto object.

Person p1 = new Person(1, "Krishna");
ModelMapper modelMapper = new ModelMapper();

PersonDto personDto = modelMapper.map(p1, PersonDto.class);

 

Find the below working application.

 

Person.java

package com.sample.app.model;

public class Person {

	private int id;
	private String name;

	public Person() {
		super();
	}

	public Person(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + "]";
	}

}

 

PersonDto.java

package com.sample.app.model;

public class PersonDto {
	private int id;
	private String name;
	
	public PersonDto() {
		super();
	}

	public PersonDto(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "PersonDto [id=" + id + ", name=" + name + "]";
	}

}

HelloWorld.java

package com.sample.app;

import java.io.IOException;

import org.modelmapper.ModelMapper;

import com.sample.app.model.Person;
import com.sample.app.model.PersonDto;

public class HelloWorld {

	public static void main(String args[]) throws IOException {
		Person p1 = new Person(1, "Krishna");
		ModelMapper modelMapper = new ModelMapper();

		PersonDto personDto = modelMapper.map(p1, PersonDto.class);
		System.out.println(personDto);

	}

}


Output

PersonDto [id=1, name=Krishna]


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment