Saturday, 5 March 2022

Dozer: Map only specific fields

By setting ‘wildcard’ attribute to false, we can restrict the dozer to map explicitly defined fields.

 

Example

<mapping wildcard="false">
	<class-a>com.sample.app.model.Employee</class-a>
	<class-b>com.sample.app.model.Person</class-b>

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

</mapping>

In the above snippet, I set the attribute ‘wildcard’ to false (wildcard is set to true by default, This means that it will automatically try to map every property in the two objects.), when dozer reads this property, it can understand that user want to map only defined fields.


 

Find the below working application.

 

Employee.java

package com.sample.app.model;

public class Employee {
	private Integer id;
	private String fName;
	private String lName;
	
	public Employee() {}

	public Employee(Integer id, String fName, String lName) {
		this.id = id;
		this.fName = fName;
		this.lName = lName;
	}

	public Integer getId() {
		return id;
	}

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

	public String getfName() {
		return fName;
	}

	public void setfName(String fName) {
		this.fName = fName;
	}

	public String getlName() {
		return lName;
	}

	public void setlName(String lName) {
		this.lName = lName;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", fName=" + fName + ", lName=" + lName + "]";
	}
	
	

}

Person.java

package com.sample.app.model;

public class Person {
	private Integer id;
	private String firstName;
	private String lastName;

	public Person() {
	}

	public Person(Integer id, String firstName, String lastName) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public Integer getId() {
		return id;
	}

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

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

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

}

map-defined-fields-only.xml

<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://dozer.sourceforge.net
      http://dozer.sourceforge.net/schema/beanmapping.xsd">

	<mapping wildcard="false">
		<class-a>com.sample.app.model.Employee</class-a>
		<class-b>com.sample.app.model.Person</class-b>

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

	</mapping>

</mappings>

MapSpecificFieldDemo.java

package com.sample.app;

import java.io.IOException;
import java.util.Arrays;

import org.dozer.DozerBeanMapper;

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

public class MapSpecificFieldDemo {

	public static void main(String[] args) throws IOException {

		DozerBeanMapper mapper = new DozerBeanMapper();
		mapper.setMappingFiles(Arrays.asList("map-defined-fields-only.xml"));

		Employee employee = new Employee(1, "Arjun", "Gurram");
		Person person = mapper.map(employee, Person.class);

		System.out.println(employee);
		System.out.println(person);

	}

}

Output

Employee [id=1, fName=Arjun, lName=Gurram]
Person [id=null, firstName=Arjun, lastName=null]

As you see above snippet, only fName is mapped by Dozer.





  

Previous                                                 Next                                                 Home

Dozer: Exploring xml based mappings

 In upcoming posts, I am going to cover how to setup custom mappings in xml files. When two data models do not share common properties, we need to setup a custom mapping xml file and specify the conversions. This mapping file is used by dozer at runtime while conversion.

Previous                                                 Next                                                 Home

Thursday, 3 March 2022

Dozer: Map collection of objects

Right now I do not see a direct way to map collection of objects. But using the below generic method, we can convert collection of objects.

public static <T, U> List<U> map(final Mapper mapper, final List<T> source, final Class<U> destType) {

	final List<U> dest = new ArrayList<>();

	for (T element : source) {
		dest.add(mapper.map(element, destType));
	}

	return dest;
}

 


 

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 + "]";
	}

}

MapCollectionsDemo.java

package com.sample.app;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;

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

public class MapCollectionsDemo {

	public static <T, U> List<U> map(final Mapper mapper, final List<T> source, final Class<U> destType) {

		final List<U> dest = new ArrayList<>();

		for (T element : source) {
			dest.add(mapper.map(element, destType));
		}

		return dest;
	}

	public static void main(String args[]) {
		Type1 type1 = new Type1(10, 50);
		Type1 type2 = new Type1(20, 60);
		Type1 type3 = new Type1(30, 70);
		Type1 type4 = new Type1(40, 80);

		List<Type1> type1Objects = Arrays.asList(type1, type2, type3, type4);

		DozerBeanMapper mapper = new DozerBeanMapper();

		List<Type2> type2Objects = map(mapper, type1Objects, Type2.class);

		System.out.println("Printing Type1 objects");
		type1Objects.stream().forEach(System.out::println);

		System.out.println("\n\nPrinting Type2 objects");
		type2Objects.stream().forEach(System.out::println);

	}

}

Output

Printing Type1 objects
Type1 [a=10, b=50]
Type1 [a=20, b=60]
Type1 [a=30, b=70]
Type1 [a=40, b=80]


Printing Type2 objects
Type2 [a=10, b=50]
Type2 [a=20, b=60]
Type2 [a=30, b=70]
Type2 [a=40, b=80]



 

Previous                                                 Next                                                 Home

Wednesday, 2 March 2022

Dozer: Specify custom type converter using xml file

In this post, I am going to explain how to specify custom converter in an xml file.

 

Step 1: Define custom converter by implementing CustomConverter interface.

public class AppLogToTransactionLogConverter implements CustomConverter {

	@Override
	public Object convert(Object destination, Object source, Class<?> destinationClass, Class<?> sourceClass) {

		if (source instanceof AppLog) {
			AppLog appLog = (AppLog) source;

			return new TransactionLog(appLog.getLogMessage(),
					Date.from(Instant.ofEpochMilli(appLog.getCreatedTimeInMillis())));

		}

		else if (source instanceof TransactionLog) {
			TransactionLog transactionLog = (TransactionLog) source;
			return new AppLog(transactionLog.getMessage(), transactionLog.getCreatedDate().getTime());
		}
		
		throw new IllegalArgumentException("Invalid types");
	}

}

 

Step 2: Specify the converter in xml file.

<configuration>
	<custom-converters>
		<converter
			type="com.sample.app.converter.AppLogToTransactionLogConverter">
			<class-a>com.sample.app.model.TransactionLog</class-a>
			<class-b>com.sample.app.model.AppLog</class-b>
		</converter>
	</custom-converters>
</configuration>

  In the above snippet, I am defining AppLogToTransactionLogConverter can be used to convert TransactionLog to AppLog instances and vice versa.

 


Find the below working application.

 

Step 1: Define AppLog and TransactionLog classes.

 

AppLog.java

package com.sample.app.model;

public class AppLog {

	private String logMessage;
	private long createdTimeInMillis;

	public AppLog() {
	}

	public AppLog(String logMessage, long createdTimeInMillis) {
		this.logMessage = logMessage;
		this.createdTimeInMillis = createdTimeInMillis;
	}

	public String getLogMessage() {
		return logMessage;
	}

	public void setLogMessage(String logMessage) {
		this.logMessage = logMessage;
	}

	public long getCreatedTimeInMillis() {
		return createdTimeInMillis;
	}

	public void setCreatedTimeInMillis(long createdTimeInMillis) {
		this.createdTimeInMillis = createdTimeInMillis;
	}

	@Override
	public String toString() {
		return "AppLog [logMessage=" + logMessage + ", createdTimeInMillis=" + createdTimeInMillis + "]";
	}

}

 

TransactionLog.java

package com.sample.app.model;

import java.util.Date;

public class TransactionLog {
	private String message;
	private Date createdDate;

	public TransactionLog() {
	}

	public TransactionLog(String message, Date createdDate) {
		this.message = message;
		this.createdDate = createdDate;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Date getCreatedDate() {
		return createdDate;
	}

	public void setCreatedDate(Date createdDate) {
		this.createdDate = createdDate;
	}

	@Override
	public String toString() {
		return "TransactionLog [message=" + message + ", createdDate=" + createdDate + "]";
	}

}

 

Step 2: Define custom converter.

 

AppLogToTransactionLogConverter.java

 

package com.sample.app.converter;

import java.time.Instant;
import java.util.Date;

import org.dozer.CustomConverter;

import com.sample.app.model.AppLog;
import com.sample.app.model.TransactionLog;

public class AppLogToTransactionLogConverter implements CustomConverter {

	@Override
	public Object convert(Object destination, Object source, Class<?> destinationClass, Class<?> sourceClass) {

		if (source instanceof AppLog) {
			AppLog appLog = (AppLog) source;

			return new TransactionLog(appLog.getLogMessage(),
					Date.from(Instant.ofEpochMilli(appLog.getCreatedTimeInMillis())));

		}

		else if (source instanceof TransactionLog) {
			TransactionLog transactionLog = (TransactionLog) source;
			return new AppLog(transactionLog.getMessage(), transactionLog.getCreatedDate().getTime());
		}
		
		throw new IllegalArgumentException("Invalid types");
	}

}

 

Step 3: Specify converter details in the configuration file.

 

appLog-to-transactionLog-mapping.xml

<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://dozer.sourceforge.net
      http://dozer.sourceforge.net/schema/beanmapping.xsd">

	<configuration>
		<custom-converters>
			<converter
				type="com.sample.app.converter.AppLogToTransactionLogConverter">
				<class-a>com.sample.app.model.TransactionLog</class-a>
				<class-b>com.sample.app.model.AppLog</class-b>
			</converter>
		</custom-converters>
	</configuration>

</mappings>

 

Step 4: Define TypeConverterDemo class.

 

TypeConverterDemo.java

package com.sample.app;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;

import org.dozer.DozerBeanMapper;

import com.sample.app.model.AppLog;
import com.sample.app.model.TransactionLog;

public class TypeConverterDemo {

	public static void main(String[] args) throws IOException {
		DozerBeanMapper mapper = new DozerBeanMapper();
		mapper.setMappingFiles(Arrays.asList("appLog-to-transactionLog-mapping.xml"));
		
		TransactionLog transactionLog1 = new TransactionLog("Unable to connect to database", new Date());
		AppLog appLog = mapper.map(transactionLog1, AppLog.class);
		TransactionLog transactionLog2 = mapper.map(appLog, TransactionLog.class);

		System.out.println(transactionLog1);
		System.out.println(appLog);
		System.out.println(transactionLog2);
	}
}

 

Output

TransactionLog [message=Unable to connect to database, createdDate=Sun Feb 06 12:30:40 IST 2022]
AppLog [logMessage=Unable to connect to database, createdTimeInMillis=1644130840006]
TransactionLog [message=Unable to connect to database, createdDate=Sun Feb 06 12:30:40 IST 2022]

 

 

Previous                                                 Next                                                 Home