Exposed 0.56.0 Help

Entity definition

Representing database tables as Kotlin objects ensures type safety and allows you to work with database records just like regular Kotlin objects, taking full advantage of Kotlin's language features.

When using the DAO approach, IdTable needs to be associated with an Entity, because every database record in this table needs to be mapped to an Entity instance, identified by its primary key.

An entity instance is defined as a class. In the following example, StarWarsFilmEntity is the entity class linked to the table StarWarsFilmsTable:

package org.example.entities import org.example.tables.StarWarsFilmsTable import org.jetbrains.exposed.dao.IntEntity import org.jetbrains.exposed.dao.IntEntityClass import org.jetbrains.exposed.dao.id.EntityID class StarWarsFilmEntity(id: EntityID<Int>) : IntEntity(id) { companion object : IntEntityClass<StarWarsFilmEntity>(StarWarsFilmsTable) var sequelId by StarWarsFilmsTable.sequelId var name by StarWarsFilmsTable.name var director by StarWarsFilmsTable.director }
import org.jetbrains.exposed.dao.id.IntIdTable const val MAX_VARCHAR_LENGTH = 50 object StarWarsFilmsTable : IntIdTable() { val sequelId = integer("sequel_id").uniqueIndex() val name = varchar("name", MAX_VARCHAR_LENGTH) val director = varchar("director", MAX_VARCHAR_LENGTH) }
  • Since StarWarsFilmsTable is an IntIdTable, the StarWarsFilmsEntity class extends from IntEntity, which indicates that the id and primary key of StarWarsFilmsTable is of type Int.

  • The companion object block defines an EntityClass which is responsible for maintaining the relation between the StarWarsFilmsEntity class and the actual table object, StarWarsFilmsTable.

  • Each column in the table is represented as a property in the class, where the by keyword ensures the data is fetched or updated from the corresponding column when accessed.

Once the entity class is defined, instances of this class allow you to manipulate individual records from the corresponding table. This could involve creating a new record, retrieving a row based on its primary key, updating values, or deleting records.

Last modified: 30 October 2024