Menu

DBAdaptType and DBTypeAdaptor Adapt Types

Some schemas seem pathological, everything has a bizarre name and when there is a sensible name the data is crazy.

Say, for instance, that your database has a column called REG_DATE but the values are integers around the 40,000 mark. After much searching you work out that the values are the number of days since the 1st of January 1900.

So you have a date that is represented by an integer and all your Java is going to be converting from the integer to the more appropriate Date. And then you realise all the other tables have a similar column...

Fortunately DBvolution can help.

The @DBAdaptType annotation allows you convert from the database's QueryableDatatype to the class you want automatically, so your code only uses your preferred class.

Using the common example of a boolean stored as 'Y' or 'N', we start with:

@DBColumn("yn_column")
public DBString YNColumn= new DBString();

To convert that to a DBBoolean change it to:

@DBColumn("yn_column")
@DBAdaptType(value=MyAdaptor.class)
public DBBoolean YNColumn= new DBBoolean();

Pretty simple, just add an @DBAdaptType and treat YNColumn like it was DBBoolean the whole time. @DBAdaptType is an annotation and they can only take a handful of types, so remember to add the .class.

The hard part is, of course, writing MyAdaptor. Except it's not. It only has 2 methods and they're pretty obvious: one from the string to the boolean, and one from the boolean to the string.

public class MyAdaptor implements DBTypeAdaptor<Boolean, String=""> {

private static final long serialVersionUID = 1L;

@Override
public Boolean fromDatabaseValue(String dbvValue) {
    if (dbvValue == null) {
        return null;
    }

    return dbvValue.equals("Y");
}

@Override
public String toDatabaseValue(Boolean objectValue) {
    if (objectValue == null) {
        return null;
    } else {
        if (objectValue == true) {
            return "Y";
        } else {
            return "N";
        }
    }
}

}

DBAdaptType automatically works out the classes involved, so you don't even have to mention them. The adaptor can be re-used throughout your schema correcting multiple problems easily and transparently.

Posted by Gregory Graham 2014-04-27

Anonymous
Anonymous

Add attachments
Cancel





Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.