[FIXED] Convert One Entity to Another Entity in Java

Issue

I have 2 different Entity Class as below :

@Table(name = "tableA")
public class EntityA{

    @PartitionKey
    @Column(name = "age")
    int age;

    @PartitionKey
    @Column(name = "class")
    int class;

    @Column(name = "rollNo")
    int rollNo;

}

@Table(name = "tableB")
public class EntityA{

    @PartitionKey
    @Column(name = "class")
    int class;

    @Column(name = "rollNo")
    int rollNo;

    // one column less 
}

Now based on some condition I need to persist the data in both the tables.

In my service layer I have a List of EntityA :: List<EntityA> which I am passing to the DAOImpl method where I insert the data as below :

public void insertListItems(List<EntityA> entityAList) {
    // here I need to convert the List<EntityA>  to List<EntityB>
    // before table insert operation.
}

How I can make that conversion where in the EnitityB I have one column less. I don’t want to write boilerplate code for the conversion as my entity class is big in actual. Instead use some library that helps with the mapping.

Solution

You can use Jackson’s ObjectMapper library to achieve this. In order for this to work you must have getters declared in both EntityA and EntityB class, as well as a default (empty) constructor.

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
/**
 * Function converts list of objects to another list of objects
 * which' type is specified by the clazz attribute. Clazz attribute
 * must not be null, or it will throw a NullPointerException.
 * 
 * @param list List of target objects
 * @param clazz Class to map list objects to
 * @param <T> Target class
 * @param <F> From class
 * @return F.class List converted to T.class List
 */
public static <T, F> List<T> convertList(List<F> list, Class<T> clazz) {
    Objects.requireNonNull(clazz);
    ObjectMapper mapper = new ObjectMapper();

    // Important: this must be declared so mapper doesn't throw 
    // an exception for all properties which it can't map.
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return Optional.ofNullable(list)
            .orElse(Collections.emptyList())
            .stream()
            .map(obj -> mapper.convertValue(obj, clazz))
            .collect(Collectors.toList());
}
public void insertListItems(List<EntityA> entityAList) {
    List<EntityB> entityBList = convertList(entityAList, EntityB.class);
    // Continue with table insert operation
}

Answered By – BrunoT

Answer Checked By – David Goodson (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published