DSL
Table
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.
Table is located in the org.jetbrains.exposed.v1.core package of the exposed-core module.
The following example defines a table with an auto-incrementing integer id column and string name and email column:
object Customer : Table("customers") {
val id = integer("id").autoIncrement()
val name = text("name")
val email = text("email").uniqueIndex()
}Insert
Exposed provides several functions to insert rows into a table:
Insert a single row
To create a new table row, use the .insert() function:
suspendTransaction(database) {
Customer.insert {
it[name] = "Mary"
it[email] = "mary@xtec.dev"
}
}The .insert() function returns a InsertStatement object that contains the inserted row’s primary key value.
val id = Customer.insert {
it[name] = "Susan"
it[email] = "susan@xtec.dev"
} get Customer.id // or }.get(Customer.id)If the same row already exists in the table, it throws an exception.
Batch insert
.batchInsert() allows mapping a list of entities into table rows in a single SQL statement.
It is more efficient than using the insert query for each row as it initiates only one statement.
suspendTransaction {
val customers = listOf(
Pair("John", "john@xtec.dev"),
Pair("Anne", "anne@xtec.dev")
)
Customer.batchInsert(customers) { (name, email) ->
this[Customer.name] = name
this[Customer.email] = email
}
}You're reading a preview.
Sign in with Google to read the full page. A Google account includes 5 free pages in total; students and teachers read their course pages without limit.
Sign in