Thursday, August 11, 2016

Supporting hibernate precision/scale for BigDecimal with MySql

When we use BigDecimal in our POJOs, we define the precision /scale  values for it to make sure how many digits database column has to allocate to represent the values. MySql does not support the scale more than 2 digits, we can have only  19/2 for BigDecimal Data types.

@Column(name = "metre" ,precision = 19, scale = 10)
private BigDecimal metre = BigDecimal.ZERO;


To overcome this issue, we can convert BigDecimal datatype to Double when we store the values. JPA provides @Convert annotation which can be used to convert datatypes .

Eg: 

@Convert(converter = BigDecimalConverter.class)
private  BigDecimal metre = BigDecimal.ZERO;


We need to write a custom converter for this.

Converter


import java.math.BigDecimal;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter
public class BigDecimalConverter implements AttributeConverter {

@Override
public Double convertToDatabaseColumn(BigDecimal bigDecimalValue) {
if (bigDecimalValue == null) {
return null;
}

return bigDecimalValue.doubleValue();
}

@Override
public BigDecimal convertToEntityAttribute(Double doubleValue) {
if (doubleValue == null) {
return null;
}

return BigDecimal.valueOf(doubleValue);
}

}

2 comments: