Skip to content

Instantly share code, notes, and snippets.

@aoudiamoncef
Last active April 24, 2024 08:23
Show Gist options
  • Save aoudiamoncef/c07edc90157ec2c7dfa83a2e3b4f89c8 to your computer and use it in GitHub Desktop.
Save aoudiamoncef/c07edc90157ec2c7dfa83a2e3b4f89c8 to your computer and use it in GitHub Desktop.
BigDecimal Scale 2 && RoundingMode.HALF_UP Hibernate Converter
package com.maoudia;
import java.math.BigDecimal;
import java.math.RoundingMode;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
@Converter(autoApply = true)
public class BigDecimalConverter implements AttributeConverter<BigDecimal, BigDecimal> {
@Override
public BigDecimal convertToDatabaseColumn(BigDecimal attribute) {
if (attribute == null) {
return null;
}
return attribute.setScale(2, RoundingMode.HALF_UP);
}
@Override
public BigDecimal convertToEntityAttribute(BigDecimal dbData) {
if (dbData.scale() == 2) {
return dbData;
} else {
return dbData.setScale(2, RoundingMode.HALF_UP);
}
}
}
package com.maoudia;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.math.RoundingMode;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class BigDecimalConverterTest {
private final BigDecimalConverter converter = new BigDecimalConverter();
@Test
public void testConvertToDatabaseColumn() {
assertNull(converter.convertToDatabaseColumn(null));
assertEquals(new BigDecimal("123.46"), converter.convertToDatabaseColumn(new BigDecimal("123.456")));
assertEquals(new BigDecimal("123.46"), converter.convertToDatabaseColumn(new BigDecimal("123.464")));
assertEquals(new BigDecimal("123.46"), converter.convertToDatabaseColumn(new BigDecimal("123.46")));
assertEquals(new BigDecimal("123.47"), converter.convertToDatabaseColumn(new BigDecimal("123.465")));
}
@Test
public void testConvertToEntityAttribute() {
assertEquals(new BigDecimal("123.46"), converter.convertToEntityAttribute(new BigDecimal("123.456")));
assertEquals(new BigDecimal("123.46"), converter.convertToEntityAttribute(new BigDecimal("123.464")));
assertEquals(new BigDecimal("123.46"), converter.convertToEntityAttribute(new BigDecimal("123.46")));
assertEquals(new BigDecimal("123.47"), converter.convertToEntityAttribute(new BigDecimal("123.465")));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment