-
Notifications
You must be signed in to change notification settings - Fork 0
Table Creation
Santiago Escobares edited this page Apr 5, 2025
·
1 revision
mysql-wrapper provides a Table interface inteded to be implemented on enum classes. You will need to set up a name for each table, as well as a List<TableColumn> out of persistent instances and a List<String> for some additional table settings.
We will first define some columns for a table called "users" that will be created later.
class UserColumns {
static final TableColumn ID = TableColumn.Builder.of("id", TableType.SMALLINT)
.build();
static final TableColumn NAME = TableColumn.Builder.of("name", TableType.CHAR)
.typeData("16") // Char type length. typeData is var-arged.
.notNull()
.build();
static final TableColumn CREATION_DATE = TableColumn.Builder.of("creation_date", TableType.TIMESTAMP)
.defaultValue("CURRENT_TIMESTAMP")
.notNull()
.build();
static final TableColumn PASSWORD = TableColumn.Builder.of("password", TableType.CHAR)
.typeData("25")
.notNull()
.build();
}Now, we have to create an implementation for Table
import static columns.package.UserColumns.*;
enum Tables implements Table {
USERS(
"users",
Arrays.asList(
ID,
NAME,
CREATION_DATE,
PASSWORD
),
Collections.singletonList(
"PRIMARY KEY (id)"
)
);
private final String name;
private final List<TableColumn> columns;
private final List<String> options;
public Tables(String name, List<TableColumn> columns, List<String> options) {
this.name = name;
this.columns = columns;
this.options = options;
}
@Override
public String getName() {
return this.name;
}
@Override
public List<TableColumn> getColumns() {
return this.columns;
}
@Override
public List<String> getOptions() {
return this.options;
}
}Finally, we create our tables in database
Database.createTables(Tables.USERS); // Var-arged