CRUD objects

com.db.crud.CRUDHandler, com.db.crud.CRUDObject (experimental)

Experimental. This is the part of JBend I was still designing when I stopped in 2022. Creating tables, storing and loading objects work and are shown below. It builds its SQL as text, so only ever give it ids that your own code generated, never text typed by a user. For anything user-facing, use ServerQuery with parameters.

The idea: describe a record as a Java class, and let a handler keep a table in step with it. The handler reads the class's fields by reflection, creates the table if it is missing, adds columns when you add fields, and turns store(), load(), save() and delete() into queries.

A record and its handler

public class Note extends CRUDObject {
    private String title, body;

    public Note(CRUDHandler h, String id, String title, String body) {
        super(h, id);
        this.title = title;
        this.body = body;
    }
    public String title() { return title; }
}
public class Notes extends CRUDHandler<Note> {

    public Notes() {
        super("notes", "id");                              // table name, key column
        assignClass(Note.class);
        setSaveFields(new String[]{"title", "body"});     // the fields that become columns
    }

    @Override
    public void start() {                                  // called once the table is ready
        Note n = new Note(this, "n1", "Shopping", "milk, eggs");
        n.store();                                         // INSERT

        final Note again = new Note(this, "n1", "", "");
        again.LOAD(x -> {                                  // SELECT, then this runs
            Console.output("Notes", again.title());
            return null;
        });
    }
}
dataserver:
source env:DB_DSN

app:
class com.example.Notes

A handler is a thread in the start sequence like any other: it checks its table when its turn comes and calls start() when the table is ready.

What the handler does at startup

Table stateAction
MissingCreated: an id column (VARCHAR(63), primary key) and one VARCHAR(128) column per saved field.
Fewer columns than fieldsThe missing columns are added.
More columns than fieldsThe extra columns are dropped. Remove a field and its data goes with it.
A column of a different typeReported in the log, never changed automatically.

setTypeForField("body", "TEXT") in the handler's constructor gives a field a column type other than the default.

Object methods

MethodDoes
store()Inserts the object as a new row.
load()Reads the row with this object's id into its fields, then calls onLoad(), which you can override.
LOAD(function)The same, calling the function with the object when it has loaded.
save()Updates the row from the object's fields.
delete()Deletes the row.

Set CRUDHandler.DEBUG_CRUD = true to log every step and every statement.