Last active
April 24, 2024 08:23
-
-
Save aoudiamoncef/c07edc90157ec2c7dfa83a2e3b4f89c8 to your computer and use it in GitHub Desktop.
BigDecimal Scale 2 && RoundingMode.HALF_UP Hibernate Converter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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