I have a User and UserDTO class but in dto class i dont want to user LocalDateTime, i want to convert it to long type. (because protobuf not support date). So in code:
My User entity class:
public class User {
private String name,password;
private LocalDateTime date;
//getters-setters, tostring..
}
My DTO:
public class UserDTO {
private String name,password;
private long date;
//getters-setters, tostring..
}
And you see that the date in entity User is LocalDateTime, and in DTO is long. I want to use this dozermapper:
UserDTO destObject =
mapper.map(user, UserDTO.class);
The LocalDateTime changing code to long:
private static long setDateToLong(LocalDateTime date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
String dateString = date.format(formatter);
return Long.parseLong(dateString);
}
Is it possible that the mapper knows that change the LocalDateTime to long? Can i somehow configure it? Thanks for the helps!
Finally i found a sollution which is create from LocalDateTime to String and back from String to LocalDateTime. I have to create a converter:
public class DozerConverter implements CustomConverter {
@Override
public Object convert(Object destination, Object source, Class destClass, Class sourceClass) {
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
if(source instanceof String) {
String sourceTime = (String) source;
return LocalDateTime.parse(sourceTime, formatter);
} else if (source instanceof LocalDateTime) {
LocalDateTime sourceTime = (LocalDateTime) source;
return sourceTime.toString();
}
return null;
}
}
And in my custom xml i have to add the custom-converter attribute like this one:
<?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>
<class-a>mypackage.UserDTO</class-a>
<class-b>mypackage.User</class-b>
<field custom-converter="mypackage.DozerConverter">
<a>lastLoggedInTime</a>
<b>lastLoggedInTime</b>
</field>
</mapping>
</mappings>
I think it can work with any data types, just have to write more converter, or write this converter smart.