Search code examples
javaannotationsmetadatadata-annotationsjava-6

How create a converter with Annotation?


I would like to create a anotation that converter from boolean to String. For example

public User {
    @Id
    @Column(name="user_name")
    private String name;

    @Column(name="active")
    //This the CustomAnnotation
    @ConvertMyBooleanToString
    private boolean isActive;
}

My Custom Annotation

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME) 
public @interface ConvertMyBooleanToString {
    //empty
}

Implementation somewhere

...
return valueFieldThatHasAnnotation ? "Yes" : "No";
...

So, I do not know how to implement this annotation so that every time before saving to the database, it does the conversion to a String.

Thanks guys!


Solution

  • How are you persisting to the database? If you are using hibernate, there is a built-in "yes_no" type

    yes_no: A type that maps an SQL CHAR(1) to a Java Boolean.

    So something like:

    @Type(type="yes_no")
    public boolean isActive;