With MentaBean you can create a table in the database from your bean mappings through the session.createTable(bean) or session.createTables() methods. Depending on the dialect you are using, the appropriate create table SQL will be generated and executed. See some examples below:
BeanConfig config = new BeanConfig(User.class, "Users"); config.pk("id", DBTypes.AUTOINCREMENT); config.field("username", DBTypes.STRING); config.field("birthdate", "bd", DBTypes.DATE); // note that the database column name is different config.field("status", new EnumIdType(Status.class)); config.field("deleted", DBTypes.BOOLEANINT); config.field("insertTime", "insert_time", DBTypes.NOW_ON_INSERT_TIMESTAMP); config.field("updateTime", "update_time", DBTypes.NOW_ON_UPDATE_TIMESTAMP); // (...) BeanSession session = new H2BeanSession(beanManager, conn); session.createTable(User.class);
create table Users (
id integer AUTO_INCREMENT NOT NULL,
username varchar(200),
bd date,
status smallint NOT NULL,
deleted smallint,
insert_time timestamp,
update_time timestamp
);
alter table Users add primary key (id);
For columns that support a size attribute, you can pass the size through the Fluent API in your mappings. You can also specify whether the column can be null or not. For example, for the username column we want the size to be 50 and we do not want to allow NULLs. The mappings and the generated SQL are shown below:
BeanConfig config = new BeanConfig(User.class, "Users"); config.pk("id", DBTypes.AUTOINCREMENT); config.field("username", DBTypes.STRING.size(50).nullable(false)); config.field("birthdate", "bd", DBTypes.DATE); // note that the database column name is different config.field("status", new EnumIdType(Status.class)); config.field("deleted", DBTypes.BOOLEANINT); config.field("insertTime", "insert_time", DBTypes.NOW_ON_INSERT_TIMESTAMP); config.field("updateTime", "update_time", DBTypes.NOW_ON_UPDATE_TIMESTAMP); // (...) BeanSession session = new H2BeanSession(beanManager, conn); session.createTable(User.class);
create table Users (
id integer AUTO_INCREMENT NOT NULL,
username varchar(50) NOT NULL,
bd date,
status smallint NOT NULL,
deleted smallint,
insert_time timestamp,
update_time timestamp
);
alter table Users add primary key (id);
NOTE: MentaBean can also create tables with compound primary keys. If more than one property was defined for the bean as the primary key (compound PK), they will be included in the SQL above that creates the PK.