abeld89
abeld89

Reputation: 87

Mapping a property using an expression of MapStructs

class Product {
    Object obj;
}

class Object {
    Float amount;
}

class ObjectDto {
    Integer price;
}

class ProductMapper{

    @Mapping(expression = "java(this.convert(dto.getObject().getPrice(), decimals))", target = "object.amount")
    public abstract Product(ProductDto dto, decimals);

    protected Float convert(Integer price, decimals){
        price.floatValue();
    }
}

I'm trying to map by a Mapstruct expression an Integer to Float passing to a function the parameters and decimals but when the implementation is generated is not arriving correctly the parameter "decimals" and I can not map it.

It is possible?

The code of implementation looks like this:

class ProductMapperImpl {
    method(ObjectDto objectDto, Integer decimals){
        product.setObject(objectDtoToObject(dto.getObject()));
    }
    Object objectDtoToObject(ObjectDto objectDto){
        Object obj = new Object();
        obj.setAmount (this.convert(objectDto.getPrice());
    }
}

Upvotes: 0

Views: 4483

Answers (1)

Sjaak
Sjaak

Reputation: 4170

So, what about this (this is what I meant originally):


@Mapper
public abstract class ProductMapper{

    @Mapping( target = "amount", source = "object.price" ); 
    public abstract Product toProduct(ProductDto dto, @Context Integer decimals);

    public Float createPrice(Integer price, @Context Integer decimals) {
       // do some Float stuff here
    }

}

BTW: I would not use a Float for an amount, but always a BigDecimal.. Just google on float / amount..

Upvotes: 2

Related Questions