3. Converter Code

There are two simple interfaces, Converter and ListConverter, used to copy to and from two different types classes. This provides a clear interface for the application to interact with even though Dozer is the primary implementation, it provides some flexibility for other possible implementations. Such as converting a JSON String to and from a class.

Example 1. Converter in Spring by Example REST Module

Simple interface for converting to and from any two classes.

                
public interface Converter<T, V> {

    /**
     * Converts from a domain model to the business model.
     */
    public V convertTo(T source);

    /**
     * Converts from a business model to the domain model.
     */
    public T convertFrom(V source);

}
                
            

Example 2. ListConverter in Spring by Example REST Module

Simple interface for converting to and from lists of any two classes.

                
public interface ListConverter<T, V> extends Converter<T, V> {

    /**
     * Converts from a domain model list to a business model list.
     */
    public List<V> convertListTo(Collection<T> list);
    
    /**
     * Converts from a business model list to a domain model list.
     */
    public List<T> convertListFrom(Collection<V> list);

}
                
            

Example 3. AbstractMapperListConverter in Spring by Example REST Module

Most converter implementations should just need to extend this class and pass in the appropriate parameters to the constructor.

                
public abstract class AbstractMapperListConverter<T, V> extends AbstractListConverter<T, V> {

    private final Mapper mapper;
    private final Class<T> tClazz;
    private final Class<V> vClazz;

    public AbstractMapperListConverter(Mapper mapper,
                                       Class<T> tClazz, Class<V> vClazz) {
        this.mapper = mapper;
        this.tClazz = tClazz;
        this.vClazz = vClazz;
    }

    @Override
    public V convertTo(T source) {
        Assert.notNull(source, "Source must not be null.");

        return mapper.map(source, vClazz);
    }

    @Override
    public T convertFrom(V source) {
        Assert.notNull(source, "Source must not be null.");
        
        return mapper.map(source, tClazz);
    }
    
}
                
            

Example 4. ContactConverter in Spring by Example REST Module

The ContactConverter converts to and from the entity and JAXB bean. It extends AbstractMapperListConverter, which basically just delegates to Dozer.

                
@Component
public class ContactConverter extends AbstractMapperListConverter<org.springbyexample.contact.orm.entity.person.Person, Person> {

    @Autowired
    public ContactConverter(Mapper mapper) {
        super(mapper, 
              org.springbyexample.contact.orm.entity.person.Person.class, Person.class);
    }
    
}