Exposed 0.55.0 Help

Defining tables

Core Table class

In Exposed, the Table class is the core abstraction for defining database tables. This class provides methods to define various column types, constraints, and other table-specific properties.

It is located in the org.jetbrains.exposed.sql package of the exposed-core module.

Exposed supports a variety of column types, including integer, varchar, bool, and more. Each column is defined by calling the appropriate method on the Table object.

The following example defines a simple table with an integer id column and a string name column:

object Cities : Table() { val id = integer("id") val name = varchar("name", 50) }

By default, Exposed will generate the table name from the full class name:

CREATE TABLE IF NOT EXISTS CITIES (ID INT NOT NULL, "name" VARCHAR(50) NOT NULL)

If the object name contains a 'Table' suffix, Exposed will omit the suffix from the generated table name:

object CitiesTable : Table() { val id = integer("id") val name = varchar("name", 50) }
CREATE TABLE IF NOT EXISTS CITIES (ID INT NOT NULL, "name" VARCHAR(50) NOT NULL)

Configure a custom table name

To configure a custom name for a table, which will be used in actual SQL queries, pass it to the name parameter of the Table() constructor.

object Cities : Table("all_cities") { val id = integer("id") val name = varchar("name", 50) }
CREATE TABLE IF NOT EXISTS ALL_CITIES (ID INT NOT NULL, "name" VARCHAR(50) NOT NULL)

Some databases, like H2, fold unquoted identifiers to upper case. To keep table name case-sensitivity, manually quote the provided argument:

object Cities : Table("\"all_cities\"") { val id = integer("id") val name = varchar("name", 50) }
CREATE TABLE IF NOT EXISTS "all_cities" (ID INT NOT NULL, "name" VARCHAR(50) NOT NULL)

Depending on what DBMS you use, the types of columns could be different in actual SQL queries.

Convenience IdTable class

While Table is the foundational class for defining tables, Exposed also provides the base IdTable convenience class. This class extends Table and is designed to simplify the definition of tables that use a standard id column as the primary key.

For example, to provide an auto-incrementing id column of type Int, you can use the IntIdTable subtype:

object StarWarsFilms : IntIdTable() { val sequelId = integer("sequel_id").uniqueIndex() val name = varchar("name", 50) val director = varchar("director", 50) }
Last modified: 25 September 2024