Monday, April 29, 2013

JPA Boolean Conversion

In some cases, we might want to store Boolean value in database as "Y/N" or "T/F" instead of "1/0".
This is to increase human readability and better support across different databases because different databases could store Boolean value in different data types.

JPA does support the "Y/N" or "T/F" as Boolean value with the help of @ObjectTypeConverter annotation.
We just need to annotate the entity class with this annotation.
@Entity
@ObjectTypeConverter(...)
public class MyEntity {
    ............................
    ............................
}

Example below shows the converter to convert "Y/N" to Boolean (true/false).
All 5 attributes are occupied, now what we need to do is simply provide values to all the attributes.
@ObjectTypeConverter(
    name = "YNBooleanConverter",
    dataType = String.class,
    objectType = Boolean.class,
    defaultObjectValue = "false",
    conversionValues = {
        @ConversionValue(dataValue = "Y", objectValue = "true"),
        @ConversionValue(dataValue = "N", objectValue = "false") })


Done!!

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...