Home JPA save BigDecimal as integer in Database
Reply: 1

JPA save BigDecimal as integer in Database

Mariano L
1#
Mariano L Published in 2017-12-07 20:45:59Z

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.

Simon Martinelli
2#
Simon Martinelli Reply to 2017-12-08 12:06:45Z

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;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.307612 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO