3

I have this field in the database:

ITEMCOST    NUMERIC (13)    DEFAULT 0  NOT NULL

In JAVA, the field in the Entity is defined like this:

@Column(name = "ITEMCOST")
private BigDecimal itemCost;

The values are stored in the database as integer. Where the last two digits are the decimal values. like this:

  • DB 100 means 1.00
  • DB 250 means 2.50
  • etc

What I want is when I read the Entity the value is loaded like that. If the value in the database is 357 the BigDeciamal should have the value "3.57". And when I save that entity, the value should be converted again as INT.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Mariano L
  • 1,809
  • 4
  • 29
  • 51

1 Answers1

4

Like the comments say you should use an Attribute converter.

Please find a description here https://www.thoughts-on-java.org/jpa-21-how-to-implement-type-converter/

It could look like this:

@Converter
public class BigDecimalConverter implements AttributeConverter<BigDecimal, Long> {

  @Override
  public Long convertToDatabaseColumn(BigDecimal value) {
    if (value == null) {
        return null;
    } else {
        return value.multiply(BigDecimal.valueOf(100)).longValue();
    }
  }

  @Override
  public BigDecimal convertToEntityAttribute(Long value) {
    if (value == null) {
        return null;
    } else {
        return new BigDecimal(value).divide(BigDecimal.valueOf(100));
    }
  }
}

Then you can use it in your entity

@Convert(converter = BigDecimalConverter.class)
@Column(name = "ITEMCOST")
private BigDecimal itemCost;
Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82