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);
}

}

Thursday, July 7, 2016

JAX-RS Custom Exception Mapper

When the service(backend) throws any custom exception, using <javax.ws.rs.ext.ExceptionMapper> we can catch it , and send a relevant message to the client (/caller).

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

/**
 * Map the server exceptions to return to the client
 *
 */

@Provider
public class CustomJaxRsExceptionMapper implements ExceptionMapper {

@Override
     @Produces("application/json")
public Response toResponse(ServiceException e) {

          Map map = new HashMap();
  map.put("Exception", e.getMessage());

Response response = Response.status(500).entity(map).build();
return response;
}
}