I just converted all of my java.math.BigDecimal
usages to javax.money.MonetaryAmount
(where they represented money). I am currently "assuming" the currency to be USD with the help of a MoneyUtils
to avoid adding extra database columns that will only contain "USD" in them. This can be seen in the next 2 snippets.
@Converter(autoApply = true)
public class MonetaryAmountConverter
implements AttributeConverter<MonetaryAmount, BigDecimal> {
@Override
public BigDecimal convertToDatabaseColumn(final MonetaryAmount monetaryAmount) {
return DefaultUtils.defaultOrNull(
monetaryAmount,
ma -> ma.getNumber().numberValue(BigDecimal.class));
}
@Override
public MonetaryAmount convertToEntityAttribute(final BigDecimal monetaryAmountValue) {
if (monetaryAmountValue == null) {
return null;
} else {
return MoneyUtils.of(monetaryAmountValue);
}
}
}
public final class MoneyUtils {
public static final CurrencyUnit DOLLAR = Monetary.getCurrency(Locale.US);
public static MonetaryAmount of(@NonNull final BigDecimal value) {
return Money.of(value, MoneyUtils.DOLLAR);
}
}
I have this @Repository
method that should give me a sum, which could be null
if no rows match:
@Query("query that can return null or a numeric")
MonetaryAmount sumSomeData();
The problem is that it doesn't go through my MonetaryAmountConverter
. I tried adding a @Convert
directly to the method but it didn't work.
@Query("query that can return null or a numeric")
@Convert(converter = MonetaryAmountConverter.class)
MonetaryAmount sumSomeData();
So it appears that an AttributeConverter
with @Converter(autoApply = true)
applies to JPA Entity fields, but not to method return types, even when @Convert
is added to the method signature.
- Is there something I am missing?
- Is there a way to do this without needing to do the conversion manually in the caller of this repository method?