blee
blee

Reputation: 11

orika property expression mapping

Given

classA {

    long fahr;
....

and

classB {
    long cels;
....

how can I map the following in Orika?

A.fahr <-> (B.cels*9)/5   

Do I need customised Mapper or Filter ?

Upvotes: 0

Views: 479

Answers (2)

Williams
Williams

Reputation: 61

I suggest to use field level converter if both are of different data types but since they are of same data type we have to use a custom converter for entire class. This is sample converter that suitable for this use case.

import ma.glasnost.orika.BoundMapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.converter.ConverterFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;

public class EntryClass {

    public static void main(String[] args) {
        EntryClass ec = new EntryClass();
        BoundMapperFacade<A, B> facade = getMapperFactory().getMapperFacade(A.class, B.class);
        A fahr = new A(455);
        B cels = facade.map(fahr);
        System.out.println(cels);
        A revFahr = facade.mapReverse(cels);
        System.out.println(revFahr);
    }

    private static MapperFactory getMapperFactory() {
        MapperFactory factory = new DefaultMapperFactory.Builder()
                                .build();
        ConverterFactory cfactory = factory.getConverterFactory();
        cfactory.registerConverter(new FahrCelsConverter());
        factory.classMap(A.class, B.class)
                .field("fahr", "cels")
                .byDefault()
                .register();
        return factory;
    }
}

public class A {

    long fahr;

    public A(long fahr) {
        this.fahr = fahr;
    }


    public long getFahr() {
        return fahr;
    }


    public void setFahr(long fahr) {
        this.fahr = fahr;
    }


    @Override
    public String toString() {
        return "A [fahr=" + fahr + "]";
    }
}

public class B {

    long cels;

    public B(long cels) {
        this.cels = cels;
    }

    public long getCels() {
        return cels;
    }

    public void setCels(long cels) {
        this.cels = cels;
    }

    @Override
    public String toString() {
        return "B [cels=" + cels + "]";
    }
}

public class FahrCelsConverter extends BidirectionalConverter<A, B>
{
@Override
public B convertTo(A source, Type<B> destinationType, MappingContext mappingContext) {      
    if(source != null)
    {
        return new B((source.fahr - 32) * 5 / 9);
    }
    return null;
}

@Override
public A convertFrom(B source, Type<A> destinationType, MappingContext mappingContext) {
    if(source != null)
    {
        return new A((source.cels / 5) * 9 + 32);
    }
    return null;
}
}

Upvotes: 1

Sidi
Sidi

Reputation: 1739

It's more suited to use a converter (by id).

Upvotes: 0

Related Questions