How can I use ObjectBox to store money values (BigDecimal)?
Asked Answered
V

1

5

To represent money value I use BigDecimal because of the accuracy (double type causes errors). So, how can I store BigDecimal value in the ObjectBox, what type of a field or converter should I use?

Vet answered 18/9, 2017 at 11:12 Comment(1)
Thanks for coming up with this. I just created a feature request.Harsho
D
6

There is no default support for BigDecimal so you have to create Converter. Here is an example:

public class BigDecimalConverter implements PropertyConverter<BigDecimal, String> {

    @Override
    public BigDecimal convertToEntityProperty(String databaseValue) {
        return new BigDecimal(databaseValue);
    }

    @Override
    public String convertToDatabaseValue(BigDecimal entityProperty) {
        return entityProperty.toString();
    }
}

@Entity
public class BigDecimalEntity {

    @Convert(dbType = String.class, converter = BigDecimalConverter.class)
    private BigDecimal decimal;

    public BigDecimal getDecimal() {
        return decimal;
    }

    public void setDecimal(BigDecimal decimal) {
        this.decimal = decimal;
    }
}
Desiredesirea answered 18/9, 2017 at 11:23 Comment(2)
So, now such complex types can be converted to a string value to be stored. That's clear. Thank you!Vet
Converting to strings seems like a terrible idea because you can't query them with > or <. Better to convert to double float, or a long.Mahout

© 2022 - 2024 — McMap. All rights reserved.