Mariano L
Mariano L

Reputation: 1879

JPA save BigDecimal as integer in Database

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:

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.

Upvotes: 3

Views: 3008

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36103

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;

Upvotes: 4

Related Questions