1

There are around 6 POJO classes (domain entities, DTO's, DMO's) all have almost same fields. To convert from one objec to another, I'm passing one object and calling its getters to set it in another object.

private UserTemp convertDmoToUserTempEntity(final UserDmo userDmo) {
    final UserTemp userTemp = new UserTemp();
    userTemp.setUsername(userDmo.getUsername());
    userTemp.setPassword(userDmo.getPassword());
    userTemp.setStatus(userDmo.getStatus());
    return userTemp;
}

private UserDmo convertEntityToUserDmo(final UserTemp userTemp) {
    final UserDmo userDmo = new UserDmo();
    userDmo.setUserId(userTemp.getUserId());
    userDmo.setUsername(userTemp.getUsername());
    userDmo.setStatus(userTemp.getStatus());
    return userDmo;
}

There are lots of these conversion like from one entity to another, DTO to DMO, DMO To DTO etc. I believe the better way to handle this would be Generics, passing source object and destination object.

public static <E, T> T convert(E e, T t) {
    //call getter of source object to set it in destination object.
    return t;
}

UserConverterImpl.convertFromTempToUser(userTemp, user);

I need help in this. When I pass object in parameter, I need a way its methods. Is there any better way to achieve this?

Vijay Nandwana
  • 2,476
  • 4
  • 25
  • 42

2 Answers2

2

You could try to use a framework for this. In the past I have used Dozer to do this.

In following post, other frameworks are mentioned as well any tool for java object to object mapping?.

(some advice: When mapping JPA entity objects, watch out for lazy fields being automatically mapped by the frameworks)

Perhaps you don't want/cannot use a separate framework for whatever reason. Since you seem to have a strict layering, you will probably have mappers for each layer. Then I would go for a separate mapping for each object. This way you can easily work out mapping from username to userId etc. The chances that all objects in the layers have exactly the same names for their methods are not that high, and likely to change anyway.

Community
  • 1
  • 1
Manuel
  • 239
  • 1
  • 4
  • Thanks for the answer. I tried using Dozer however, it was not able to auto map UUID type. I found Spring frameworks `BeanUtils` as an alternate solution. – Vijay Nandwana Apr 21 '17 at 09:05
0

Ended up using BeanUtils of Spring.

BeanUtils.copyProperties(Object source, Object target)

Vijay Nandwana
  • 2,476
  • 4
  • 25
  • 42