Search code examples
javajooq

Apply Default Values when Instantiating a new Record


I see that jOOQ is also adding the default value to its metadata:

public class Kampagne extends TableImpl<KampagneRecord> {

  this.AKTIV = createField("AKTIV", 
               SQLDataType.VARCHAR(1).nullable(false)
                 .defaultValue(DSL.field("'J' ", SQLDataType.VARCHAR)), 
               this, 
               "die Kampagne ist aktiv, d.h. noch nicht abgeschlossen (markiert) resp. ist abgeschlossen (nicht markiert)", 
               new Varchar2ToBooleanConverter());

Is there a way to add these default values when creating a new Record?

So that this test will succeed?

KampagneRecord record = new KampagneRecord();

assertTrue(record.getAktiv();

Why I need this you may ask? I use the Record in a UI and want that the checkboxes are already set to the default value based on the Record that is bound to the model.


Solution

  • This is currently not implemented. There are a variety of possible DEFAULT expressions that need to be evaluated, possibly by the database, in order to get the correct value. A simple case is CURRENT_TIMESTAMP, which should correspond:

    1. To the server (database) time, not the client time
    2. To the time the record is actually created, not some prior moment when a client creates the client record model.

    In your particular case, it would obviously work as it is a constant without any contextual ambiguity. You could extend the code generator and generate some custom code sections in records (and POJOs if you use them). That custom code section would then contain an instance initialiser, which would be run with every constructor call:

    {
        set(KAMPAGNE.AKTIV, true);
        // Other default initialisations
    }
    

    Alternatively, you could use the parser to reverse engineer the DataType.default_() value and extract the constant value from the Param (if it is a Param, or something compatible with a Param, such as e.g. CAST(1 AS INT))