Search code examples
javaactivejdbc

Doing additional operations during ActiveJDBC Model construction


I have a database with one table words, so my Model in ActiveJDBC is Word.

When a row from the database is casted to the Word model, I want to perform some additional operations, such as casting some data to enums for better abstraction.

I added a constructor to the model, which is called appropriately, but trying to access any data returns null. Here's the Word class (shortened):

public class Word extends Model {

    private static final Logger log = LogManager.getLogger(Word.class);
    public static final String SPELLING = "ortho";

    public Word() {
        log.info("In constructor");
        log.info("Word spelling: " + getSpelling());
    }

    public String getSpelling() {
        return this.getString(SPELLING);
    }
}

but I get the following in the logs:

10:31:49.372 [main] INFO Word - In constructor
10:31:49.373 [main] INFO Word - Word spelling: null

I need to be able to cast some of these fields to enums and manipulate it in other ways to have an easier time using it.

Should I leave Word as an empty class such as:

public class Word extends Model {}

and have another class take it in a constructor? That would create a lot of unnecessary cruft, especially when working with List<Word>... what's the best way to manipulate data during Model object creation in ActiveJDBC?


Solution

  • You need to use the CallbackListener or a CallbackAdapter

    Please, see the Lifecycle Callbacks page.

    The reason your SPELLING is null is because at the time of creation of the model, the attribute values are not set yet.

    What you need is something like this:

    public class Word extends Model{
       public void afterLoad(){
         String spelling = getString(SPELLING); //you have data  now
       }
    }