Table
- Kotlin course
- Advanced
- Lesson 32/83
- 5 min
Learn to define schemas with Table object.
The Table object
A Table in Exposed is declared with a Kotlin object. Each column is declared as a val property.
Example: object Users : Table() { val id = integer("id"); val name = varchar("name", 50) }. This object represents a table named users in the database. Functions like integer, varchar and bool declare column types. For a primary key use val id = integer("id").autoIncrement() and override val primaryKey = PrimaryKey(id). The table name defaults to the lowercased object name.
Column types
Exposed offers functions for common SQL types: integer, varchar, bool, long, text.
Example: val name = varchar("name", 50) declares a 50 character text column. val age = integer("age") is an integer column. val active = bool("active") is a Boolean column. For nullable columns add .nullable(). For a default value use .default(0). These declarations generate SQL DDL automatically; a separate helper call creates the table in the database.
Practice Define the Users table
Define object Users : Table(). Inside it, declare val id = integer("id") and val name = varchar("name", 50). Inside main, print println("Table ready").
Starter code
// Table
// write here
import org.jetbrains.exposed.sql.*
fun main() {
}Sample solution
object Users : Table() {
val id = integer("id")
val name = varchar("name", 50)
}
fun main() {
println("Table ready")
}Expected output
Table ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the Table definition
object Users : ____() {
val id = integer("id")
val name = varchar("name", 50)
}
object Users : Table() {
val id = integer("id")
val name = varchar("name", 50)
}
Explanation: Table declares the table base.
2 Match column types
| Term | Meaning |
|---|---|
integer |
Integer |
varchar |
Text |
bool |
Boolean |
long |
Long integer |
3 Which construct declares a table in Exposed?
- interface
- data class
- sealed class
- object : Table() Correct answer
Explanation: Tables are declared with object : Table().