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 .


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

We need to write a custom converter for this.


import java.math.BigDecimal;

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

public class BigDecimalConverter implements AttributeConverter {

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

return bigDecimalValue.doubleValue();

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

return BigDecimal.valueOf(doubleValue);


1 comment:

  1. Amazing & Great informative blog,it gives very useful practical information to developer like me. Besides that Wisen has established as Best Hibernate Training in Chennai . or learn thru Online Training mode Hibernate Online Training | Java EE Online Training. Nowadays Hibernate ORM has tons of job opportunities on various vertical industry.